feat(sandbox): isolate worker/chat execution in Docker containers with lifecycle UI

- Add Docker sandbox manager, non-root sandbox image, compose isolation, and host firewall script (#217)
- Route Bash, custom commands/scripts, stdio MCP, chat sessions, MainAgent chat, and task-scoped reporter screenshots into sandbox containers with per-task browser concurrency gate
- Enforce proxy SSRF guard against loopback, metadata, internal services, and admin port
- Add dedicated /system/sandbox management page, /chat session sandbox control, and task detail sandbox popover with progressive stats loading
This commit is contained in:
ji ruo committed 2026-12-01 21:13:21 +08:00
1 parent 6bbeac588d
commit 9c43e694a3
44 files changed
+7086 -91

No files matched your search

+20
View File
@@ -29,3 +29,23 @@ ARTEX_TOOL_MEMORY_LIMIT_MB=2048
ARTEX_TOOL_TIMEOUT_S=120
# 单条命令的进程/线程数上限(仅在 Linux cgroup v2 可委托时生效,默认 256;设为 0 关闭)
ARTEX_TOOL_PIDS_LIMIT=256
# 沙箱容器隔离(推荐 docker;单机无 Docker 可改为 local)
ARTEX_SANDBOX_MODE=docker
ARTEX_SANDBOX_IMAGE=ruoji6/artex-sandbox:latest
ARTEX_SANDBOX_NETWORK=artex-sandbox
# 必填(Docker 部署时):宿主机上 ./data 目录的绝对路径,用于给兄弟沙箱容器精确挂载单个任务目录
ARTEX_HOST_DATA_DIR=/path/to/ARTEX/data
# 可选:切换沙箱容器运行时(留空用默认 runc;填 runsc 可启用 gVisor 内核级隔离)
ARTEX_SANDBOX_RUNTIME=
# 单沙箱容器资源限额与自动停机策略
ARTEX_SANDBOX_MEMORY_MB=2048
ARTEX_SANDBOX_CPUS=2
ARTEX_SANDBOX_PIDS_LIMIT=256
ARTEX_SANDBOX_SHM_MB=512
ARTEX_SANDBOX_AUTO_STOP=true
ARTEX_SANDBOX_SESSION_IDLE_MIN=20
# 抓包代理 SSRF 防护:本机/云元数据/ARTEX 自身与 postgres 网段始终禁止;设为 true 时额外拦截其他私有网段(内网渗透保持 false)
ARTEX_PROXY_BLOCK_PRIVATE=false
# 宿主机自己的局域网 IP(可逗号分隔)。这些地址上的 :8787/:8788 会被代理拒绝,其他端口仍可当作扫描目标
ARTEX_PROXY_PROTECT_IPS=
+4 -17
View File
@@ -10,25 +10,12 @@
# cp -r web/out server/webui/dist
# CGO_ENABLED=0 GOARCH=amd64 go build -tags embedui -o dist/amd64/artex ./cmd/artex
# docker build -t artex:local .
FROM python:3.12-slim-bookworm
FROM debian:bookworm-slim
ARG TARGETARCH
# 常用工具:ripgrep / curl / vim,加一批 recon 常备件(按需增删)。
# Node 从 NodeSource 装 22.x,与前端构建使用的主版本一致。
# 主服务镜像只保留运行 ARTEX Go 控制面所需的最小基础依赖;
# 渗透工具链与 Playwright/Chromium 已拆入独立沙箱镜像(Dockerfile.sandbox)。
RUN apt-get update && apt-get install -y --no-install-recommends \
ca-certificates ripgrep curl wget vim git jq unzip \
tzdata \
dnsutils iputils-ping netcat-openbsd inetutils-telnet whois nmap \
&& curl -fsSL https://deb.nodesource.com/setup_22.x | bash - \
&& apt-get install -y --no-install-recommends nodejs \
&& rm -rf /var/lib/apt/lists/*
# 预装 Playwright MCP 与 CLI(全局),运行时优先直接调用 playwright-mcp,无需 npx 联网下载。
# 必须通过 playwright-mcp 自身的 install-browser 安装对应版本的 chromium 及其系统依赖,
# 避免全局 playwright 与 @playwright/mcp 内置 playwright-core 版本不一致导致找不到浏览器可执行文件。
RUN npm install -g @playwright/mcp@latest @playwright/cli@latest \
&& playwright-mcp --version \
&& playwright-cli --help \
&& playwright-mcp install-browser --with-deps chromium \
&& playwright-cli install-browser chromium \
ca-certificates curl tzdata \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /app
ENV TZ=Asia/Shanghai
+46
View File
@@ -0,0 +1,46 @@
# syntax=docker/dockerfile:1
#
# ARTEX Worker / Chat Sandbox 镜像:
# 承载所有不受信任的工具执行(Bash / Python 脚本 / 扫描工具 / Playwright 浏览器),
# 不含 ARTEX 主服务、不含 LLM Key、不含数据库凭据,以非 root 用户运行。
#
# 本地构建:
# docker build -f Dockerfile.sandbox -t ruoji6/artex-sandbox:latest .
FROM python:3.12-slim-bookworm
ENV TZ=Asia/Shanghai \
DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get install -y --no-install-recommends \
ca-certificates ripgrep curl wget vim git jq unzip \
tzdata procps \
dnsutils iputils-ping netcat-openbsd inetutils-telnet whois nmap \
&& curl -fsSL https://deb.nodesource.com/setup_22.x | bash - \
&& apt-get install -y --no-install-recommends nodejs \
&& rm -rf /var/lib/apt/lists/*
# 预装 Playwright MCP 与 CLI 及 Chromium(直接装到全局路径供非 root 用户运行,
# 浏览器访问目标站点完全隔离在沙箱容器内)。
# 国内构建可传 --build-arg PLAYWRIGHT_DOWNLOAD_HOST=https://npmmirror.com/mirrors/playwright 加速。
ARG PLAYWRIGHT_DOWNLOAD_HOST=""
ENV PLAYWRIGHT_BROWSERS_PATH=/ms-playwright \
PLAYWRIGHT_DOWNLOAD_HOST=${PLAYWRIGHT_DOWNLOAD_HOST}
RUN mkdir -p /ms-playwright /workspace /etc/artex \
&& npm install -g @playwright/mcp@latest @playwright/cli@latest \
&& playwright-mcp --version \
&& playwright-cli --help \
&& playwright-mcp install-browser --with-deps chromium \
&& playwright-cli install-browser chromium \
&& chmod -R a+rX /ms-playwright \
&& rm -rf /var/lib/apt/lists/*
# 常用渗透/脚本 Python 依赖
RUN pip install --no-cache-dir requests httpx beautifulsoup4 pyyaml
# 非 root 运行用户(UID/GID 1000,与 ARTEX_SANDBOX_USER 默认值对齐)。
RUN groupadd -g 1000 sandbox \
&& useradd -u 1000 -g 1000 -m -s /bin/bash sandbox \
&& chown -R 1000:1000 /workspace
USER 1000:1000
WORKDIR /workspace
CMD ["sleep", "infinity"]
+30 -4
View File
@@ -9,6 +9,7 @@ import (
"github.com/Autumn-27/artex/db"
"github.com/Autumn-27/artex/guard"
"github.com/Autumn-27/artex/intercept"
"github.com/Autumn-27/artex/internal/sandbox"
"github.com/Autumn-27/norma/agentcore"
"github.com/Autumn-27/norma/llm"
"github.com/Autumn-27/norma/permission"
@@ -111,9 +112,20 @@ func (c *ChatAgent) Chat(ctx context.Context, agentKey, sessionID, message strin
ws.Enabled = false
}
sbMgr := sandbox.Default()
sandboxActive := sbMgr != nil && sbMgr.Enabled()
sbTarget := sandbox.Target{Scope: sandbox.ScopeSession, OwnerID: sessionID}
if preset, ok := sandbox.TargetFrom(ctx); ok && preset.Valid() {
sbTarget = preset
}
// Per-session working directory: <workDir>/sessions/<sessionID>/
// Isolates file writes across conversations, mirroring how workers use i<intentID>/.
// When bound to a task sandbox (e.g. task-scoped reporter screenshots), use
// that task's workspace root so screenshots land directly in tasks/<id>/.
sessionWorkDir := filepath.Join(c.workDir, "sessions", sessionID)
if sandboxActive && sbTarget.Scope == sandbox.ScopeTask {
sessionWorkDir = sbMgr.Config().LocalRootFor(sbTarget)
}
_ = os.MkdirAll(sessionWorkDir, 0o755)
ctx = intercept.WithReviewWorkingDirectory(ctx, sessionWorkDir)
@@ -121,15 +133,30 @@ func (c *ChatAgent) Chat(ctx context.Context, agentKey, sessionID, message strin
// visible skills/MCP and lets the DB tools table filter/override. DefaultTools
// have no tools-table rows, so they always pass through.
base := guardedDefaultTools()
displayWorkDir := sessionWorkDir
displayDataDir := c.workDir
if sandboxActive {
sbMgr.Acquire(sbTarget)
defer sbMgr.Release(sbTarget)
ctx = sandbox.WithTarget(ctx, sbTarget)
hostRoot := sbMgr.Config().LocalRootFor(sbTarget)
base = wrapSandboxFileTools(base, hostRoot, "")
displayWorkDir = sandbox.ContainerWorkDir
displayDataDir = sandbox.ContainerWorkDir
}
ctx = WithRunInfo(ctx, RunInfo{SessionID: sessionID, WorkDir: sessionWorkDir})
tools, def, cleanup := AugmentTools(ctx, agentKey, base)
defer cleanup()
system, boundary := deferredSystem(chatSystem(agentKey, c.workDir, sessionWorkDir), def)
system, boundary := deferredSystem(chatSystem(agentKey, displayDataDir, displayWorkDir), def)
proxyAddr := c.proxyAddr
if c.proxyAddrFn != nil {
proxyAddr = c.proxyAddrFn()
}
bashEnv := proxyEnv(proxyAddr, c.proxyCACert)
if sandboxActive {
bashEnv = sbMgr.ProxyEnv(proxyAddr != "")
}
opts := agentcore.Options{
Provider: c.prov,
SystemPrompt: system,
@@ -148,9 +175,8 @@ func (c *ChatAgent) Chat(ctx context.Context, agentKey, sessionID, message strin
BraveSearchAPIKey: ws.BraveKey,
TavilySearchAPIKey: ws.TavilyKey,
WebSearchProxy: ws.Proxy,
BashEnv: proxyEnv(proxyAddr, c.proxyCACert), // Bash 子命令默认走代理+信任 CA
BashEnv: bashEnv, // Bash 子命令默认走代理+信任 CA
WorkingDir: sessionWorkDir,
MaxTurns: maxTurns,
MaxDuration: maxDuration,
Compaction: compactionConfig(c.window),
Todos: actool.NewTodoStore(),
+24 -4
View File
@@ -3,9 +3,11 @@ package agent
import (
"context"
"fmt"
"strconv"
"github.com/Autumn-27/artex/db"
"github.com/Autumn-27/artex/intercept"
"github.com/Autumn-27/artex/internal/sandbox"
"github.com/Autumn-27/norma/agentcore"
"github.com/Autumn-27/norma/llm"
"github.com/Autumn-27/norma/permission"
@@ -131,14 +133,32 @@ func (m *MainAgent) Chat(ctx context.Context, taskID int64, mainSeg int, as *db.
// 本任务的工作目录 <workDir>/tasks/<taskID>,先建好。
mainDir := ensureRunDir(m.workDir, taskID, 0)
ctx = intercept.WithReviewWorkingDirectory(ctx, mainDir)
displayWorkDir := mainDir
displayDataDir := m.workDir
sbMgr := sandbox.Default()
sandboxActive := sbMgr != nil && sbMgr.Enabled() && taskID > 0
if sandboxActive {
sbTarget := sandbox.Target{Scope: sandbox.ScopeTask, OwnerID: strconv.FormatInt(taskID, 10)}
sbMgr.Acquire(sbTarget)
defer sbMgr.Release(sbTarget)
ctx = sandbox.WithTarget(ctx, sbTarget)
hostRoot := sbMgr.Config().LocalRootFor(sbTarget)
base = wrapSandboxFileTools(base, hostRoot, "")
displayWorkDir = sandbox.ContainerWorkDir
displayDataDir = sandbox.ContainerWorkDir
}
ctx = WithRunInfo(ctx, RunInfo{TaskID: taskID, ExplorationID: explorationID(ts), WorkDir: mainDir})
tools, def, cleanup := AugmentTools(ctx, "mainagent", base)
defer cleanup()
system, boundary := deferredSystem(mainAgentSystem(goal, m.workDir, mainDir), def)
system, boundary := deferredSystem(mainAgentSystem(goal, displayDataDir, displayWorkDir), def)
proxyAddr := m.proxyAddr
if m.proxyAddrFn != nil {
proxyAddr = m.proxyAddrFn()
}
bashEnv := proxyEnv(proxyAddr, m.proxyCACert)
if sandboxActive {
bashEnv = sbMgr.ProxyEnv(proxyAddr != "")
}
opts := agentcore.Options{
Provider: m.prov,
SystemPrompt: system,
@@ -157,10 +177,10 @@ func (m *MainAgent) Chat(ctx context.Context, taskID int64, mainSeg int, as *db.
BraveSearchAPIKey: m.webSearch.BraveKey,
TavilySearchAPIKey: m.webSearch.TavilyKey,
WebSearchProxy: m.webSearch.Proxy,
BashEnv: proxyEnv(proxyAddr, m.proxyCACert), // Bash 子命令默认走代理+信任 CA
WorkingDir: mainDir, // 本任务工作目录 <workDir>/tasks/<taskID>
BashEnv: bashEnv, // Bash 子命令默认走代理+信任 CA
WorkingDir: mainDir, // 本任务工作目录 <workDir>/tasks/<taskID>
ToolOutputDir: cmdOutDir(mainDir),
MaxTurns: m.maxTurns, // 0 = unlimited (configurable in agent management)
MaxTurns: m.maxTurns, // 0 = unlimited (configurable in agent management)
Compaction: compactionConfig(m.compactionWindow()), // long chats stay within the window
Todos: actool.NewTodoStore(), // 会话级临时待办(TodoWrite),纯规划用,退出即丢
// 命中预算(步数)→ SDK 跑收尾:向用户输出一句进展总结。Prompt 与收尾轮数可后台编辑(默认 10 轮)。
+134
View File
@@ -0,0 +1,134 @@
package agent
import (
"context"
"encoding/json"
"fmt"
"path/filepath"
"strings"
"github.com/Autumn-27/artex/internal/sandbox"
"github.com/Autumn-27/norma/llm"
actool "github.com/Autumn-27/norma/tool"
)
// wrapSandboxFileTools confines norma's built-in filesystem tools (Read, Write,
// Edit, MultiEdit, LS, Glob, Grep) to hostRoot and translates paths between
// the container view (/workspace/...) and the host directory, enforcing symlink
// escape protection on every call.
func wrapSandboxFileTools(tools []actool.CoreTool, hostRoot, defaultSubdir string) []actool.CoreTool {
out := make([]actool.CoreTool, len(tools))
for i, t := range tools {
switch t.Name() {
case "Read", "Write", "Edit", "MultiEdit", "LS", "Glob", "Grep":
out[i] = &sandboxFileTool{
CoreTool: t,
hostRoot: filepath.Clean(hostRoot),
defaultSubdir: defaultSubdir,
}
default:
out[i] = t
}
}
return out
}
type sandboxFileTool struct {
actool.CoreTool
hostRoot string
defaultSubdir string
}
func (s *sandboxFileTool) Call(ctx context.Context, in json.RawMessage, tc *actool.ToolContext) (actool.Result, error) {
rewritten, err := s.rewriteInput(in)
if err != nil {
return actool.Errorf("Error: " + err.Error()), nil
}
// Adjust ToolContext.WorkingDir to the confined default directory on host so
// relative operations (LS/Glob/Grep without explicit path) never escape hostRoot.
subTC := tc
if tc != nil {
cp := *tc
if s.defaultSubdir != "" {
cp.WorkingDir = filepath.Join(s.hostRoot, s.defaultSubdir)
} else {
cp.WorkingDir = s.hostRoot
}
subTC = &cp
}
res, err := s.CoreTool.Call(ctx, rewritten, subTC)
if err != nil {
return res, err
}
return s.rewriteResult(res), nil
}
func (s *sandboxFileTool) rewriteInput(in json.RawMessage) (json.RawMessage, error) {
var m map[string]any
if err := json.Unmarshal(in, &m); err != nil {
return in, nil
}
changed := false
for _, key := range []string{"file_path", "path"} {
rawVal, exists := m[key]
if !exists {
continue
}
strVal, ok := rawVal.(string)
if !ok {
continue
}
if strings.TrimSpace(strVal) == "" && (s.Name() == "LS" || s.Name() == "Glob" || s.Name() == "Grep") {
if s.defaultSubdir != "" {
m[key] = filepath.Join(s.hostRoot, s.defaultSubdir)
} else {
m[key] = s.hostRoot
}
changed = true
continue
}
resolved, allowed := sandbox.ResolveConfined(s.hostRoot, s.defaultSubdir, strVal)
if !allowed {
return nil, fmt.Errorf("path %q is outside sandbox workspace (%s)", strVal, sandbox.ContainerWorkDir)
}
m[key] = resolved
changed = true
}
// If LS/Glob/Grep omitted path entirely, anchor it inside the sandbox root.
if !changed && (s.Name() == "LS" || s.Name() == "Glob" || s.Name() == "Grep") {
if _, hasPath := m["path"]; !hasPath {
if s.defaultSubdir != "" {
m["path"] = filepath.Join(s.hostRoot, s.defaultSubdir)
} else {
m["path"] = s.hostRoot
}
changed = true
}
}
if !changed {
return in, nil
}
b, err := json.Marshal(m)
if err != nil {
return in, err
}
return b, nil
}
func (s *sandboxFileTool) rewriteResult(res actool.Result) actool.Result {
rootReal, err := filepath.EvalSymlinks(s.hostRoot)
if err != nil {
rootReal = s.hostRoot
}
for i := range res.Content {
if res.Content[i].Type == llm.BlockText && res.Content[i].Text != "" {
txt := res.Content[i].Text
txt = strings.ReplaceAll(txt, rootReal, sandbox.ContainerWorkDir)
if s.hostRoot != rootReal {
txt = strings.ReplaceAll(txt, s.hostRoot, sandbox.ContainerWorkDir)
}
res.Content[i].Text = txt
}
}
return res
}
+25 -10
View File
@@ -12,6 +12,7 @@ import (
"github.com/Autumn-27/artex/db"
"github.com/Autumn-27/artex/intercept"
"github.com/Autumn-27/artex/internal/sandbox"
"github.com/Autumn-27/norma/agentcore"
"github.com/Autumn-27/norma/harness"
"github.com/Autumn-27/norma/llm"
@@ -372,6 +373,18 @@ func (w *Worker) execute(ctx context.Context, name string, taskID int64, as *db.
base = append(base, defaultToolsExcept("MultiEdit", "Glob", "Grep")...)
// 本次意图的专属工作目录 <workDir>/tasks/<taskID>/i<intentID>,引擎侧先建好。
runDir := ensureRunDir(w.workDir, taskID, intent.ID)
displayRunDir := runDir
sbMgr := sandbox.Default()
sandboxActive := sbMgr != nil && sbMgr.Enabled()
if sandboxActive {
sbTarget := sandbox.Target{Scope: sandbox.ScopeTask, OwnerID: strconv.FormatInt(taskID, 10)}
sbMgr.Acquire(sbTarget)
defer sbMgr.Release(sbTarget)
ctx = sandbox.WithTarget(ctx, sbTarget)
hostRoot := sbMgr.Config().LocalRootFor(sbTarget)
base = wrapSandboxFileTools(base, hostRoot, fmt.Sprintf("i%d", intent.ID))
displayRunDir = sandbox.HostToContainerPath(hostRoot, runDir)
}
// The run-wide intent is not the current tool action. Do not forward it or
// inherit a parent run's background into the action reviewer.
ctx = intercept.WithReviewContext(ctx, runDir, intercept.ReviewBackground{})
@@ -379,22 +392,25 @@ func (w *Worker) execute(ctx context.Context, name string, taskID int64, as *db.
tools, def, cleanup := AugmentTools(ctx, "worker", base)
defer cleanup()
// 意图是 worker 的【唯一职责、贯穿整个 run 的不变量】→ 连同启动指令、意图锚定的目标资产
// 原始数据一起放进 system prompt:system 每次 run 都重新拼一遍、绝不会被 compaction 压掉,
// 长 run 里意图永远在场,续跑时也不依赖 transcript 历史是否留住那条首消息。代价是 system
// 混入 per-intent 易变数据、失去跨意图缓存复用;这是刻意的取舍(意图丢失比省 token 严重得多)。
// 与 planner「态势块放 user turn」分叉是有意的:planner 本身是产意图的那个、没有单一 mandate,
// worker 有。仅【全局态势 overview】留在启动 user 消息里——它可降级、容忍 stale,压掉无碍。
overview := renderWorkerGraphOverview(tsx.graphOverviewData())
proxyAddr := w.proxyAddr
if w.proxyAddrFn != nil {
proxyAddr = w.proxyAddrFn()
}
sysBody := workerSystem(proxyAddr, w.proxyCACert, w.workDir, runDir)
sysProxyAddr, sysCACert, sysDataDir := proxyAddr, w.proxyCACert, w.workDir
bashEnv := proxyEnv(proxyAddr, w.proxyCACert)
if sandboxActive {
if proxyAddr != "" && sbMgr.Config().ProxyURL != "" {
sysProxyAddr = sbMgr.Config().ProxyURL
sysCACert = sandbox.ContainerCACertPath
}
sysDataDir = sandbox.ContainerWorkDir
bashEnv = sbMgr.ProxyEnv(proxyAddr != "")
}
sysBody := workerSystem(sysProxyAddr, sysCACert, sysDataDir, displayRunDir)
if w.wantConstraints() {
sysBody += constraintBlock(ts) // 操作约束(若有)注入系统提示,worker 执行时严格遵守
}
// 意图块 → 意图锚定资产块 → 启动指令,依次追加到 system 尾部(与 constraintBlock 同一套追加法)。
sysBody += renderIntentTask(intent)
if as != nil {
if ids := intentAssetIDs(intent); len(ids) > 0 {
@@ -444,9 +460,8 @@ func (w *Worker) execute(ctx context.Context, name string, taskID int64, as *db.
TavilySearchAPIKey: w.webSearch.TavilyKey,
WebSearchProxy: w.webSearch.Proxy,
// Bash 子命令的 HTTP 默认走记录代理 + 信任其 CA(工具无需 -x/-k)。
BashEnv: proxyEnv(proxyAddr, w.proxyCACert),
BashEnv: bashEnv,
WorkingDir: runDir,
MaxTurns: w.maxTurns, // 0 = unlimited (configurable in agent management)
// 墙钟预算,轮边界判,不打断半路;0 = 不限。有任务级 deadline 时夹逼到 min(自身预算,
// 距 deadline 剩余),让本 run 在任务到点时自然进收尾(见 taskclock.go)。
MaxDuration: maxDur,
+65 -5
View File
@@ -7,6 +7,8 @@ services:
POSTGRES_DB: ${POSTGRES_DB:-artex}
volumes:
- pgdata:/var/lib/postgresql/data
networks:
- artex-internal
healthcheck:
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-artex} -d ${POSTGRES_DB:-artex}"]
interval: 5s
@@ -14,16 +16,39 @@ services:
retries: 10
restart: unless-stopped
# 收敛宿主机 Docker API 权限:只暴露沙箱容器管理所需的接口,不把完整宿主机 docker.sock 直接交给主服务。
docker-socket-proxy:
image: ${ARTEX_DOCKER_PROXY_IMAGE:-tecnativa/docker-socket-proxy:latest}
environment:
CONTAINERS: 1
EXEC: 1
IMAGES: 1
NETWORKS: 1
INFO: 1
PING: 1
POST: 1
ALLOW_START: 1
ALLOW_STOP: 1
ALLOW_RESTARTS: 1
volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro
networks:
- artex-internal
restart: unless-stopped
artex:
image: ${ARTEX_IMAGE:-ruoji6/artex}:${ARTEX_TAG:-latest}
depends_on:
postgres:
condition: service_healthy
docker-socket-proxy:
condition: service_started
environment:
TZ: Asia/Shanghai
ARTEX_PG_DSN: postgres://${POSTGRES_USER:-artex}:${POSTGRES_PASSWORD}@postgres:5432/${POSTGRES_DB:-artex}?sslmode=disable
ANTHROPIC_API_KEY: ${ANTHROPIC_API_KEY:-}
OPENAI_API_KEY: ${OPENAI_API_KEY:-}
GEMINI_API_KEY: ${GEMINI_API_KEY:-}
ARTEX_LLM_PROVIDER: ${ARTEX_LLM_PROVIDER:-}
ARTEX_LLM_MODEL: ${ARTEX_LLM_MODEL:-}
ARTEX_LLM_BASE_URL: ${ARTEX_LLM_BASE_URL:-}
@@ -32,9 +57,27 @@ services:
ARTEX_TOOL_MEMORY_LIMIT_MB: ${ARTEX_TOOL_MEMORY_LIMIT_MB:-}
ARTEX_TOOL_TIMEOUT_S: ${ARTEX_TOOL_TIMEOUT_S:-}
ARTEX_TOOL_PIDS_LIMIT: ${ARTEX_TOOL_PIDS_LIMIT:-}
# 沙箱容器隔离配置(子 Agent 的 Bash / 文件 / 脚本 / Playwright 在独立容器内执行)
ARTEX_SANDBOX_MODE: ${ARTEX_SANDBOX_MODE:-docker}
ARTEX_DOCKER_HOST: ${ARTEX_DOCKER_HOST:-http://docker-socket-proxy:2375}
ARTEX_SANDBOX_IMAGE: ${ARTEX_SANDBOX_IMAGE:-ruoji6/artex-sandbox:latest}
ARTEX_SANDBOX_NETWORK: ${ARTEX_SANDBOX_NETWORK:-artex-sandbox}
ARTEX_SANDBOX_RUNTIME: ${ARTEX_SANDBOX_RUNTIME:-}
# auto 自动探测 artex-sandbox 网桥网关地址(如 http://172.30.0.1:8788),兼容 enable_icc=false
ARTEX_SANDBOX_PROXY_URL: ${ARTEX_SANDBOX_PROXY_URL:-auto}
ARTEX_HOST_DATA_DIR: ${ARTEX_HOST_DATA_DIR:?请在 .env 设置宿主机 ./data 绝对路径 ARTEX_HOST_DATA_DIR}
ARTEX_SANDBOX_MEMORY_MB: ${ARTEX_SANDBOX_MEMORY_MB:-2048}
ARTEX_SANDBOX_CPUS: ${ARTEX_SANDBOX_CPUS:-2}
ARTEX_SANDBOX_PIDS_LIMIT: ${ARTEX_SANDBOX_PIDS_LIMIT:-256}
ARTEX_SANDBOX_SHM_MB: ${ARTEX_SANDBOX_SHM_MB:-512}
ARTEX_SANDBOX_AUTO_STOP: ${ARTEX_SANDBOX_AUTO_STOP:-true}
ARTEX_SANDBOX_SESSION_IDLE_MIN: ${ARTEX_SANDBOX_SESSION_IDLE_MIN:-20}
ARTEX_PROXY_BLOCK_PRIVATE: ${ARTEX_PROXY_BLOCK_PRIVATE:-false}
# 宿主机局域网地址。这些地址上的其他端口仍可扫描;:8787 / :8788 由抓包代理拒绝,避免沙箱借代理回连管理口。
ARTEX_PROXY_PROTECT_IPS: ${ARTEX_PROXY_PROTECT_IPS:-}
ports:
- "8787:8787"
- "127.0.0.1:8788:8788"
- "8788:8788"
volumes:
# 把数据目录(含 jwt.key、SQLite 等)绑定到项目根目录的 data/,
# 方便在宿主机直接查看/备份,容器重建也不丢。
@@ -42,12 +85,29 @@ services:
# 把项目根目录的 skills 挂进容器(覆盖镜像内置的 /app/skills);
# 改 skill 无需重建镜像,容器读的就是宿主机这份。
- ./skills:/app/skills
# 容器级内存/进程上限,防止单个重工具(如 innoextract/7z/playwright/ffuf)打满宿主机内存并触发 swap 抖动。
# memswap_limit 与 mem_limit 保持一致以禁止容器吃宿主机 swap;可通过 .env 中的 ARTEX_MEMORY_LIMIT / ARTEX_PIDS_LIMIT 调整。
mem_limit: ${ARTEX_MEMORY_LIMIT:-4g}
memswap_limit: ${ARTEX_MEMORY_LIMIT:-4g}
networks:
- artex-internal
# 主服务已剥离重工具链,资源上限主要用于控制面进程
mem_limit: ${ARTEX_MEMORY_LIMIT:-2g}
memswap_limit: ${ARTEX_MEMORY_LIMIT:-2g}
pids_limit: ${ARTEX_PIDS_LIMIT:-512}
restart: unless-stopped
networks:
artex-internal:
driver: bridge
artex-sandbox:
name: ${ARTEX_SANDBOX_NETWORK:-artex-sandbox}
driver: bridge
ipam:
config:
- subnet: ${ARTEX_SANDBOX_SUBNET:-172.30.0.0/16}
gateway: ${ARTEX_SANDBOX_GATEWAY:-172.30.0.1}
driver_opts:
# 关闭沙箱容器间互通,防止被反制的任务容器横向攻击其他任务容器。
# 沙箱经网桥网关访问宿主机上发布的 :8788 抓包代理。
# 宿主机还需执行 scripts/artex-sandbox-firewall.sh,丢掉沙箱网桥到 :8787、
# 内部网络(postgres / docker-socket-proxy)和 169.254.169.254 的直连。
com.docker.network.bridge.enable_icc: "false"
volumes:
pgdata:
+490
View File
@@ -0,0 +1,490 @@
package sandbox
import (
"bufio"
"bytes"
"context"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"strings"
"sync"
"time"
)
const dockerAPIVersion = "/v1.43"
// dockerClient is a minimal, zero-dependency Docker Engine HTTP client supporting
// both Unix domain sockets (unix:///var/run/docker.sock) and TCP endpoints
// (http://docker-socket-proxy:2375 or tcp://host:2375).
type dockerClient struct {
scheme string // "unix" or "tcp"
address string // socket path or host:port
http *http.Client
}
func newDockerClient(dockerHost string) (*dockerClient, error) {
raw := strings.TrimSpace(dockerHost)
if raw == "" {
raw = "unix:///var/run/docker.sock"
}
dc := &dockerClient{}
switch {
case strings.HasPrefix(raw, "unix://"):
dc.scheme = "unix"
dc.address = strings.TrimPrefix(raw, "unix://")
case strings.HasPrefix(raw, "tcp://"):
dc.scheme = "tcp"
dc.address = strings.TrimPrefix(raw, "tcp://")
case strings.HasPrefix(raw, "http://"):
u, err := url.Parse(raw)
if err != nil {
return nil, fmt.Errorf("invalid docker host %q: %w", raw, err)
}
dc.scheme = "tcp"
dc.address = u.Host
default:
return nil, fmt.Errorf("unsupported docker host scheme: %q", raw)
}
tr := &http.Transport{
DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
var d net.Dialer
if dc.scheme == "unix" {
return d.DialContext(ctx, "unix", dc.address)
}
return d.DialContext(ctx, "tcp", dc.address)
},
MaxIdleConns: 16,
IdleConnTimeout: 60 * time.Second,
DisableCompression: true,
ResponseHeaderTimeout: 30 * time.Second,
}
dc.http = &http.Client{Transport: tr}
return dc, nil
}
func (c *dockerClient) dialRaw(ctx context.Context) (net.Conn, error) {
var d net.Dialer
if c.scheme == "unix" {
return d.DialContext(ctx, "unix", c.address)
}
return d.DialContext(ctx, "tcp", c.address)
}
func (c *dockerClient) doJSON(ctx context.Context, method, path string, reqBody, out any) (int, []byte, error) {
var bodyReader io.Reader
if reqBody != nil {
b, err := json.Marshal(reqBody)
if err != nil {
return 0, nil, err
}
bodyReader = bytes.NewReader(b)
}
req, err := http.NewRequestWithContext(ctx, method, "http://docker"+dockerAPIVersion+path, bodyReader)
if err != nil {
return 0, nil, err
}
if reqBody != nil {
req.Header.Set("Content-Type", "application/json")
}
resp, err := c.http.Do(req)
if err != nil {
return 0, nil, err
}
defer resp.Body.Close()
data, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
if err != nil {
return resp.StatusCode, nil, err
}
if resp.StatusCode >= 400 {
var derr struct {
Message string `json:"message"`
}
_ = json.Unmarshal(data, &derr)
msg := strings.TrimSpace(derr.Message)
if msg == "" {
msg = strings.TrimSpace(string(data))
}
return resp.StatusCode, data, &dockerAPIError{Status: resp.StatusCode, Message: msg}
}
if out != nil && len(data) > 0 {
if err := json.Unmarshal(data, out); err != nil {
return resp.StatusCode, data, err
}
}
return resp.StatusCode, data, nil
}
type dockerAPIError struct {
Status int
Message string
}
func (e *dockerAPIError) Error() string {
return fmt.Sprintf("docker api %d: %s", e.Status, e.Message)
}
func isDockerNotFound(err error) bool {
var de *dockerAPIError
return errors.As(err, &de) && de.Status == http.StatusNotFound
}
func isDockerNotModified(err error) bool {
var de *dockerAPIError
return errors.As(err, &de) && de.Status == http.StatusNotModified
}
func (c *dockerClient) Ping(ctx context.Context) error {
_, _, err := c.doJSON(ctx, http.MethodGet, "/_ping", nil, nil)
return err
}
// dockerNetworkInspect holds the subset of network fields we inspect.
type dockerNetworkInspect struct {
ID string `json:"Id"`
Name string `json:"Name"`
IPAM struct {
Config []struct {
Subnet string `json:"Subnet"`
Gateway string `json:"Gateway"`
} `json:"Config"`
} `json:"IPAM"`
}
func (c *dockerClient) InspectNetwork(ctx context.Context, name string) (*dockerNetworkInspect, error) {
var out dockerNetworkInspect
_, _, err := c.doJSON(ctx, http.MethodGet, "/networks/"+url.PathEscape(name), nil, &out)
if err != nil {
return nil, err
}
return &out, nil
}
// EnsureNetwork ensures the isolated sandbox bridge network exists with ICC disabled.
func (c *dockerClient) EnsureNetwork(ctx context.Context, name string) (*dockerNetworkInspect, error) {
if info, err := c.InspectNetwork(ctx, name); err == nil {
return info, nil
} else if !isDockerNotFound(err) {
return nil, err
}
payload := map[string]any{
"Name": name,
"CheckDuplicate": true,
"Driver": "bridge",
"Options": map[string]string{
"com.docker.network.bridge.enable_icc": "false",
},
"Labels": map[string]string{
"artex.managed": "true",
},
}
if _, _, err := c.doJSON(ctx, http.MethodPost, "/networks/create", payload, nil); err != nil {
if info, err2 := c.InspectNetwork(ctx, name); err2 == nil {
return info, nil
}
return nil, err
}
return c.InspectNetwork(ctx, name)
}
type dockerContainerInspect struct {
ID string `json:"Id"`
Name string `json:"Name"`
Created string `json:"Created"`
State struct {
Status string `json:"Status"`
Running bool `json:"Running"`
Paused bool `json:"Paused"`
StartedAt string `json:"StartedAt"`
ExitCode int `json:"ExitCode"`
} `json:"State"`
Config struct {
Image string `json:"Image"`
Labels map[string]string `json:"Labels"`
} `json:"Config"`
HostConfig struct {
Runtime string `json:"Runtime"`
NetworkMode string `json:"NetworkMode"`
Memory int64 `json:"Memory"`
} `json:"HostConfig"`
}
func (c *dockerClient) InspectContainer(ctx context.Context, idOrName string) (*dockerContainerInspect, error) {
var out dockerContainerInspect
_, _, err := c.doJSON(ctx, http.MethodGet, "/containers/"+url.PathEscape(idOrName)+"/json", nil, &out)
if err != nil {
return nil, err
}
return &out, nil
}
type dockerContainerListItem struct {
ID string `json:"Id"`
Names []string `json:"Names"`
Image string `json:"Image"`
State string `json:"State"`
Status string `json:"Status"`
Created int64 `json:"Created"`
Labels map[string]string `json:"Labels"`
}
func (c *dockerClient) ListContainersByLabel(ctx context.Context, labels map[string]string) ([]dockerContainerListItem, error) {
labelList := make([]string, 0, len(labels))
for k, v := range labels {
if v == "" {
labelList = append(labelList, k)
} else {
labelList = append(labelList, k+"="+v)
}
}
filtersJSON, _ := json.Marshal(map[string][]string{"label": labelList})
path := "/containers/json?all=true&filters=" + url.QueryEscape(string(filtersJSON))
var out []dockerContainerListItem
_, _, err := c.doJSON(ctx, http.MethodGet, path, nil, &out)
return out, err
}
func (c *dockerClient) CreateContainer(ctx context.Context, name string, spec map[string]any) (string, error) {
var resp struct {
ID string `json:"Id"`
}
_, _, err := c.doJSON(ctx, http.MethodPost, "/containers/create?name="+url.QueryEscape(name), spec, &resp)
return resp.ID, err
}
func (c *dockerClient) StartContainer(ctx context.Context, idOrName string) error {
_, _, err := c.doJSON(ctx, http.MethodPost, "/containers/"+url.PathEscape(idOrName)+"/start", nil, nil)
if isDockerNotModified(err) {
return nil
}
return err
}
func (c *dockerClient) StopContainer(ctx context.Context, idOrName string, timeoutSec int) error {
if timeoutSec <= 0 {
timeoutSec = 5
}
path := fmt.Sprintf("/containers/%s/stop?t=%d", url.PathEscape(idOrName), timeoutSec)
_, _, err := c.doJSON(ctx, http.MethodPost, path, nil, nil)
if isDockerNotModified(err) || isDockerNotFound(err) {
return nil
}
return err
}
func (c *dockerClient) RemoveContainer(ctx context.Context, idOrName string) error {
path := "/containers/" + url.PathEscape(idOrName) + "?force=true&v=true"
_, _, err := c.doJSON(ctx, http.MethodDelete, path, nil, nil)
if isDockerNotFound(err) {
return nil
}
return err
}
type dockerStats struct {
CPUPercent float64
MemUsageBytes uint64
MemLimitBytes uint64
PidsCurrent uint64
}
func (c *dockerClient) ContainerStats(ctx context.Context, idOrName string) (dockerStats, error) {
var raw struct {
CPUStats struct {
CPUUsage struct {
TotalUsage uint64 `json:"total_usage"`
} `json:"cpu_usage"`
SystemCPUUsage uint64 `json:"system_cpu_usage"`
OnlineCPUs uint32 `json:"online_cpus"`
} `json:"cpu_stats"`
PreCPUStats struct {
CPUUsage struct {
TotalUsage uint64 `json:"total_usage"`
} `json:"cpu_usage"`
SystemCPUUsage uint64 `json:"system_cpu_usage"`
} `json:"precpu_stats"`
MemoryStats struct {
Usage uint64 `json:"usage"`
Limit uint64 `json:"limit"`
Stats map[string]uint64 `json:"stats"`
} `json:"memory_stats"`
PidsStats struct {
Current uint64 `json:"current"`
} `json:"pids_stats"`
}
_, _, err := c.doJSON(ctx, http.MethodGet, "/containers/"+url.PathEscape(idOrName)+"/stats?stream=false", nil, &raw)
if err != nil {
return dockerStats{}, err
}
cpuDelta := float64(0)
if raw.CPUStats.CPUUsage.TotalUsage > raw.PreCPUStats.CPUUsage.TotalUsage {
cpuDelta = float64(raw.CPUStats.CPUUsage.TotalUsage - raw.PreCPUStats.CPUUsage.TotalUsage)
}
sysDelta := float64(0)
if raw.CPUStats.SystemCPUUsage > raw.PreCPUStats.SystemCPUUsage {
sysDelta = float64(raw.CPUStats.SystemCPUUsage - raw.PreCPUStats.SystemCPUUsage)
}
cpus := float64(raw.CPUStats.OnlineCPUs)
if cpus == 0 {
cpus = 1
}
cpuPct := 0.0
if sysDelta > 0 && cpuDelta > 0 {
cpuPct = (cpuDelta / sysDelta) * cpus * 100.0
}
memUsage := raw.MemoryStats.Usage
if inactive := raw.MemoryStats.Stats["inactive_file"]; inactive > 0 && memUsage > inactive {
memUsage -= inactive
}
return dockerStats{
CPUPercent: cpuPct,
MemUsageBytes: memUsage,
MemLimitBytes: raw.MemoryStats.Limit,
PidsCurrent: raw.PidsStats.Current,
}, nil
}
type dockerExecCreateReq struct {
AttachStdin bool `json:"AttachStdin"`
AttachStdout bool `json:"AttachStdout"`
AttachStderr bool `json:"AttachStderr"`
Tty bool `json:"Tty"`
Env []string `json:"Env,omitempty"`
Cmd []string `json:"Cmd"`
WorkingDir string `json:"WorkingDir,omitempty"`
User string `json:"User,omitempty"`
}
func (c *dockerClient) ExecCreate(ctx context.Context, containerID string, req dockerExecCreateReq) (string, error) {
var resp struct {
ID string `json:"Id"`
}
_, _, err := c.doJSON(ctx, http.MethodPost, "/containers/"+url.PathEscape(containerID)+"/exec", req, &resp)
return resp.ID, err
}
type dockerExecInspect struct {
ID string `json:"ID"`
Running bool `json:"Running"`
ExitCode int `json:"ExitCode"`
Pid int `json:"Pid"`
}
func (c *dockerClient) ExecInspect(ctx context.Context, execID string) (dockerExecInspect, error) {
var out dockerExecInspect
_, _, err := c.doJSON(ctx, http.MethodGet, "/exec/"+url.PathEscape(execID)+"/json", nil, &out)
return out, err
}
// ExecStartStream hijacks a raw HTTP/1.1 connection to POST /exec/<id>/start
// and demultiplexes Docker's 8-byte framed stdout/stderr stream while keeping
// the connection writable for stdin.
func (c *dockerClient) ExecStartStream(ctx context.Context, execID string) (*hijackedExec, error) {
conn, err := c.dialRaw(ctx)
if err != nil {
return nil, err
}
body := `{"Detach":false,"Tty":false}`
reqStr := fmt.Sprintf(
"POST %s/exec/%s/start HTTP/1.1\r\nHost: docker\r\nConnection: Upgrade\r\nUpgrade: tcp\r\nContent-Type: application/json\r\nContent-Length: %d\r\n\r\n%s",
dockerAPIVersion, url.PathEscape(execID), len(body), body,
)
if _, err := io.WriteString(conn, reqStr); err != nil {
conn.Close()
return nil, err
}
br := bufio.NewReaderSize(conn, 64*1024)
resp, err := http.ReadResponse(br, &http.Request{Method: http.MethodPost})
if err != nil {
conn.Close()
return nil, err
}
if resp.StatusCode != http.StatusSwitchingProtocols && resp.StatusCode != http.StatusOK {
errBody, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
conn.Close()
return nil, fmt.Errorf("docker exec start failed (%d): %s", resp.StatusCode, strings.TrimSpace(string(errBody)))
}
stdoutR, stdoutW := io.Pipe()
stderrR, stderrW := io.Pipe()
done := make(chan error, 1)
go func() {
err := demuxDockerStream(br, stdoutW, stderrW)
_ = stdoutW.Close()
_ = stderrW.Close()
done <- err
}()
return &hijackedExec{
conn: conn,
stdout: stdoutR,
stderr: stderrR,
done: done,
}, nil
}
type hijackedExec struct {
conn net.Conn
stdout io.ReadCloser
stderr io.ReadCloser
done chan error
closeOnce sync.Once
}
func (h *hijackedExec) Write(p []byte) (int, error) {
return h.conn.Write(p)
}
func (h *hijackedExec) CloseWrite() error {
if cw, ok := h.conn.(interface{ CloseWrite() error }); ok {
return cw.CloseWrite()
}
return nil
}
func (h *hijackedExec) Close() error {
var err error
h.closeOnce.Do(func() {
err = h.conn.Close()
})
return err
}
// demuxDockerStream parses Docker's non-TTY multiplexed stream protocol:
// each frame has an 8-byte header [streamType, 0, 0, 0, len(uint32 BE)].
func demuxDockerStream(r io.Reader, stdout, stderr io.Writer) error {
var hdr [8]byte
for {
_, err := io.ReadFull(r, hdr[:])
if err != nil {
if errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) {
return nil
}
return err
}
n := int64(binary.BigEndian.Uint32(hdr[4:8]))
var dst io.Writer
switch hdr[0] {
case 1:
dst = stdout
case 2:
dst = stderr
default:
dst = io.Discard
}
if n > 0 {
if _, err := io.CopyN(dst, r, n); err != nil {
if errors.Is(err, io.EOF) {
return nil
}
return err
}
}
}
}
File diff suppressed because it is too large. Load diff
+224
View File
@@ -0,0 +1,224 @@
package sandbox
import (
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
)
// ResolveConfined maps candidate (which may be relative to root, relative to
// defaultSubdir, or rooted at ContainerWorkDir "/workspace") to an absolute
// path inside root, verifying that neither lexical traversal ("..") nor any
// existing symlink component escapes root.
func ResolveConfined(root, defaultSubdir, candidate string) (string, bool) {
rootClean := filepath.Clean(root)
if rootClean == "" || rootClean == "." {
return "", false
}
rootReal, err := evalDeepest(rootClean)
if err != nil {
return "", false
}
raw := strings.TrimSpace(candidate)
var joined string
switch {
case raw == "" || raw == ".":
if defaultSubdir != "" {
joined = filepath.Join(rootClean, defaultSubdir)
} else {
joined = rootClean
}
case raw == ContainerWorkDir || strings.HasPrefix(raw, ContainerWorkDir+"/"):
rel := strings.TrimPrefix(raw, ContainerWorkDir)
rel = strings.TrimPrefix(rel, "/")
joined = filepath.Join(rootClean, filepath.FromSlash(rel))
case filepath.IsAbs(raw):
cleaned := filepath.Clean(raw)
if !isWithin(rootClean, cleaned) && !isWithin(rootReal, cleaned) {
return "", false
}
joined = cleaned
default:
if defaultSubdir != "" {
joined = filepath.Join(rootClean, defaultSubdir, filepath.FromSlash(raw))
} else {
joined = filepath.Join(rootClean, filepath.FromSlash(raw))
}
}
joined = filepath.Clean(joined)
if !isWithin(rootClean, joined) && !isWithin(rootReal, joined) {
return "", false
}
resolved, err := evalDeepest(joined)
if err != nil {
return "", false
}
if !isWithin(rootReal, resolved) {
return "", false
}
return resolved, true
}
// CheckPathWithinRoot verifies an already-resolved host path stays within root
// after resolving symlinks (blocking symlink escape attacks from sandbox containers).
func CheckPathWithinRoot(root, candidate string) (string, bool) {
rootClean := filepath.Clean(root)
rootReal, err := evalDeepest(rootClean)
if err != nil {
return "", false
}
resolved, err := evalDeepest(filepath.Clean(candidate))
if err != nil {
return "", false
}
if !isWithin(rootReal, resolved) {
return "", false
}
return resolved, true
}
// HostToContainerPath maps a host path under targetRoot to its container-visible
// "/workspace/..." path. Returns ContainerWorkDir if hostPath equals targetRoot.
func HostToContainerPath(targetRoot, hostPath string) string {
rootClean := filepath.Clean(targetRoot)
hostClean := filepath.Clean(hostPath)
rel, err := filepath.Rel(rootClean, hostClean)
if err != nil || rel == "." || strings.HasPrefix(rel, "..") {
return ContainerWorkDir
}
return ContainerWorkDir + "/" + filepath.ToSlash(rel)
}
// MapDataPathToHost translates a path inside artex's local DataDir to the
// corresponding host filesystem path for Docker bind mounts.
func (c Config) MapDataPathToHost(localPath string) string {
localClean := filepath.Clean(localPath)
dataClean := filepath.Clean(c.DataDir)
hostClean := filepath.Clean(c.HostDataDir)
if dataClean == hostClean {
return localClean
}
if localClean == dataClean {
return hostClean
}
rel, err := filepath.Rel(dataClean, localClean)
if err != nil || strings.HasPrefix(rel, "..") {
return localClean
}
return filepath.Join(hostClean, rel)
}
// LocalRootFor returns the local filesystem directory backing a Target inside DataDir.
func (c Config) LocalRootFor(t Target) string {
switch t.Scope {
case ScopeTask:
return filepath.Join(c.DataDir, "tasks", t.OwnerID)
case ScopeSession:
return filepath.Join(c.DataDir, "sessions", t.OwnerID)
case ScopeEphemeral:
return filepath.Join(c.DataDir, "ephemeral", sanitizeToken(t.OwnerID))
default:
return filepath.Join(c.DataDir, "ephemeral", sanitizeToken(t.OwnerID))
}
}
// CopyRegularFileSafe copies a regular file (refusing symlinks, sockets, FIFOs,
// and directories) from srcPath (confined to srcRoot) into dstDir under dstRoot,
// choosing a unique non-clobbering filename. Returns the relative path inside dstRoot.
func CopyRegularFileSafe(srcRoot, srcPath, dstRoot, dstSubdir string) (string, error) {
resolvedSrc, ok := ResolveConfined(srcRoot, "", srcPath)
if !ok {
return "", errors.New("source path escapes allowed root")
}
lfi, err := os.Lstat(resolvedSrc)
if err != nil {
return "", err
}
if !lfi.Mode().IsRegular() {
return "", fmt.Errorf("refusing non-regular file: %s", filepath.Base(resolvedSrc))
}
dstDir := filepath.Join(filepath.Clean(dstRoot), dstSubdir)
if err := os.MkdirAll(dstDir, 0o777); err != nil {
return "", err
}
if _, ok := CheckPathWithinRoot(dstRoot, dstDir); !ok {
return "", errors.New("destination escapes allowed root")
}
base := filepath.Base(resolvedSrc)
ext := filepath.Ext(base)
stem := strings.TrimSuffix(base, ext)
dstPath := filepath.Join(dstDir, base)
for i := 1; ; i++ {
if _, err := os.Lstat(dstPath); os.IsNotExist(err) {
break
}
dstPath = filepath.Join(dstDir, fmt.Sprintf("%s-%d%s", stem, i, ext))
}
in, err := os.Open(resolvedSrc)
if err != nil {
return "", err
}
defer in.Close()
out, err := os.OpenFile(dstPath, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o666)
if err != nil {
return "", err
}
if _, err := io.Copy(out, in); err != nil {
out.Close()
_ = os.Remove(dstPath)
return "", err
}
if err := out.Close(); err != nil {
_ = os.Remove(dstPath)
return "", err
}
rel, err := filepath.Rel(filepath.Clean(dstRoot), dstPath)
if err != nil {
return "", err
}
return filepath.ToSlash(rel), nil
}
// evalDeepest resolves symlinks for the deepest existing ancestor of p and
// re-attaches any non-existent trailing path components.
func evalDeepest(p string) (string, error) {
p = filepath.Clean(p)
if real, err := filepath.EvalSymlinks(p); err == nil {
return real, nil
}
var tail []string
cur := p
for {
parent := filepath.Dir(cur)
if parent == cur {
return p, nil
}
tail = append([]string{filepath.Base(cur)}, tail...)
cur = parent
if real, err := filepath.EvalSymlinks(cur); err == nil {
parts := append([]string{real}, tail...)
return filepath.Clean(filepath.Join(parts...)), nil
}
}
}
func isWithin(root, candidate string) bool {
if candidate == root {
return true
}
sep := string(os.PathSeparator)
if strings.HasSuffix(root, sep) {
return strings.HasPrefix(candidate, root)
}
return strings.HasPrefix(candidate, root+sep)
}
+136
View File
@@ -0,0 +1,136 @@
package sandbox
import (
"bytes"
"encoding/binary"
"os"
"path/filepath"
"testing"
)
func TestResolveConfinedBlocksTraversalAndSymlinkEscape(t *testing.T) {
tmp := t.TempDir()
root := filepath.Join(tmp, "tasks", "42")
outside := filepath.Join(tmp, "secret.txt")
if err := os.MkdirAll(filepath.Join(root, "i10"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(outside, []byte("top-secret"), 0o600); err != nil {
t.Fatal(err)
}
// Symlink inside workspace pointing outside
escapeLink := filepath.Join(root, "i10", "evil.txt")
if err := os.Symlink(outside, escapeLink); err != nil {
t.Fatal(err)
}
// Symlink directory pointing outside
escapeDir := filepath.Join(root, "escape-dir")
if err := os.Symlink(tmp, escapeDir); err != nil {
t.Fatal(err)
}
// Valid container paths
got, ok := ResolveConfined(root, "i10", "/workspace/i10/out.txt")
if !ok {
t.Fatalf("expected valid container path to resolve")
}
wantReal, _ := filepath.EvalSymlinks(filepath.Join(root, "i10"))
if got != filepath.Join(wantReal, "out.txt") {
t.Fatalf("got %q, want %q", got, filepath.Join(wantReal, "out.txt"))
}
// Relative path resolves under defaultSubdir
gotRel, ok := ResolveConfined(root, "i10", "notes.md")
if !ok || gotRel != filepath.Join(wantReal, "notes.md") {
t.Fatalf("relative resolve got (%q, %v)", gotRel, ok)
}
// Blocked cases: traversal, outside abs path, symlink file, symlink dir + new leaf
for _, bad := range []string{
"../../secret.txt",
"/etc/passwd",
outside,
"/workspace/i10/evil.txt",
"evil.txt",
"/workspace/escape-dir/secret.txt",
"/workspace/escape-dir/new-file.txt",
} {
if p, ok := ResolveConfined(root, "i10", bad); ok {
t.Fatalf("expected %q to be rejected, got %q", bad, p)
}
}
}
func TestCopyRegularFileSafeSkipsSymlinksAndDeduplicates(t *testing.T) {
tmp := t.TempDir()
srcRoot := filepath.Join(tmp, "sessions", "conv-1")
dstRoot := filepath.Join(tmp, "tasks", "99")
if err := os.MkdirAll(filepath.Join(srcRoot, "uploads"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(dstRoot, 0o755); err != nil {
t.Fatal(err)
}
srcFile := filepath.Join(srcRoot, "uploads", "targets.txt")
if err := os.WriteFile(srcFile, []byte("example.com\n"), 0o644); err != nil {
t.Fatal(err)
}
outside := filepath.Join(tmp, "jwt.key")
if err := os.WriteFile(outside, []byte("secret"), 0o600); err != nil {
t.Fatal(err)
}
sym := filepath.Join(srcRoot, "uploads", "link.txt")
if err := os.Symlink(outside, sym); err != nil {
t.Fatal(err)
}
rel1, err := CopyRegularFileSafe(srcRoot, "/workspace/uploads/targets.txt", dstRoot, "uploads")
if err != nil || rel1 != "uploads/targets.txt" {
t.Fatalf("first copy = (%q, %v)", rel1, err)
}
rel2, err := CopyRegularFileSafe(srcRoot, "uploads/targets.txt", dstRoot, "uploads")
if err != nil || rel2 != "uploads/targets-1.txt" {
t.Fatalf("dedup copy = (%q, %v)", rel2, err)
}
if _, err := CopyRegularFileSafe(srcRoot, "uploads/link.txt", dstRoot, "uploads"); err == nil {
t.Fatalf("expected symlink copy to be rejected")
}
}
func TestDemuxDockerStream(t *testing.T) {
var raw bytes.Buffer
writeFrame := func(kind byte, msg string) {
var hdr [8]byte
hdr[0] = kind
binary.BigEndian.PutUint32(hdr[4:8], uint32(len(msg)))
raw.Write(hdr[:])
raw.WriteString(msg)
}
writeFrame(1, "hello ")
writeFrame(2, "warn!")
writeFrame(1, "world")
var stdout, stderr bytes.Buffer
if err := demuxDockerStream(&raw, &stdout, &stderr); err != nil {
t.Fatal(err)
}
if stdout.String() != "hello world" || stderr.String() != "warn!" {
t.Fatalf("stdout=%q stderr=%q", stdout.String(), stderr.String())
}
}
func TestHostToContainerAndDataPathMapping(t *testing.T) {
cfg := Config{
DataDir: "/app/data",
HostDataDir: "/srv/artex/data",
}
if got := cfg.MapDataPathToHost("/app/data/tasks/12"); got != "/srv/artex/data/tasks/12" {
t.Fatalf("MapDataPathToHost = %q", got)
}
if got := HostToContainerPath("/app/data/tasks/12", "/app/data/tasks/12/i7"); got != "/workspace/i7" {
t.Fatalf("HostToContainerPath = %q", got)
}
if got := HostToContainerPath("/app/data/tasks/12", "/app/data/tasks/12"); got != "/workspace" {
t.Fatalf("HostToContainerPath root = %q", got)
}
}
+312
View File
@@ -0,0 +1,312 @@
package sandbox
import (
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"os"
"path/filepath"
"strconv"
"strings"
"time"
)
// Mode controls whether agent execution runs locally or inside isolated Docker containers.
type Mode string
const (
ModeLocal Mode = "local"
ModeDocker Mode = "docker"
)
// Scope identifies what owns a sandbox container.
type Scope string
const (
ScopeTask Scope = "task"
ScopeSession Scope = "session"
ScopeEphemeral Scope = "ephemeral"
)
// ContainerWorkDir is the canonical workspace mount point inside every sandbox container.
const ContainerWorkDir = "/workspace"
// ContainerCACertPath is where the recording MITM proxy CA cert is mounted read-only.
const ContainerCACertPath = "/etc/artex/ca.crt"
// Target identifies a logical sandbox instance.
type Target struct {
Scope Scope
OwnerID string
}
func (t Target) Valid() bool {
return t.Scope != "" && strings.TrimSpace(t.OwnerID) != ""
}
func (t Target) Key() string {
return string(t.Scope) + ":" + t.OwnerID
}
// Config configures the sandbox manager. Env vars supply startup defaults;
// persisted DB settings can override mutable runtime fields via ApplyOverrides.
type Config struct {
Mode Mode
DockerHost string
Image string
Network string
Runtime string
DataDir string
HostDataDir string
ProxyURL string
CACertPath string
MemoryMB int
CPUs float64
PidsLimit int
ShmSizeMB int
TmpSizeMB int
User string
AutoStopOnComplete bool
SessionIdleMinutes int
InstanceID string
}
// RuntimeOverrides carries settings editable from the Settings UI / API.
type RuntimeOverrides struct {
Image *string `json:"image,omitempty"`
MemoryMB *int `json:"memory_mb,omitempty"`
CPUs *float64 `json:"cpus,omitempty"`
PidsLimit *int `json:"pids_limit,omitempty"`
ShmSizeMB *int `json:"shm_size_mb,omitempty"`
Runtime *string `json:"runtime,omitempty"`
AutoStopOnComplete *bool `json:"auto_stop_on_complete,omitempty"`
SessionIdleMinutes *int `json:"session_idle_minutes,omitempty"`
}
// ConfigFromEnv builds a Config from environment variables with safe defaults.
func ConfigFromEnv(dataDir, caCertPath string) Config {
mode := Mode(strings.ToLower(strings.TrimSpace(os.Getenv("ARTEX_SANDBOX_MODE"))))
if mode != ModeDocker {
mode = ModeLocal
}
dockerHost := strings.TrimSpace(os.Getenv("ARTEX_DOCKER_HOST"))
if dockerHost == "" {
dockerHost = strings.TrimSpace(os.Getenv("DOCKER_HOST"))
}
if dockerHost == "" {
dockerHost = "unix:///var/run/docker.sock"
}
hostDataDir := strings.TrimSpace(os.Getenv("ARTEX_HOST_DATA_DIR"))
if hostDataDir == "" {
hostDataDir = dataDir
}
image := strings.TrimSpace(os.Getenv("ARTEX_SANDBOX_IMAGE"))
if image == "" {
image = "ruoji6/artex-sandbox:latest"
}
network := strings.TrimSpace(os.Getenv("ARTEX_SANDBOX_NETWORK"))
if network == "" {
network = "artex-sandbox"
}
user := strings.TrimSpace(os.Getenv("ARTEX_SANDBOX_USER"))
if user == "" {
user = "1000:1000"
}
instanceID := strings.TrimSpace(os.Getenv("ARTEX_SANDBOX_INSTANCE"))
if instanceID == "" {
sum := sha256.Sum256([]byte(filepath.Clean(hostDataDir)))
instanceID = hex.EncodeToString(sum[:4])
}
return Config{
Mode: mode,
DockerHost: dockerHost,
Image: image,
Network: network,
Runtime: strings.TrimSpace(os.Getenv("ARTEX_SANDBOX_RUNTIME")),
DataDir: filepath.Clean(dataDir),
HostDataDir: filepath.Clean(hostDataDir),
ProxyURL: strings.TrimSpace(os.Getenv("ARTEX_SANDBOX_PROXY_URL")),
CACertPath: strings.TrimSpace(caCertPath),
MemoryMB: envInt("ARTEX_SANDBOX_MEMORY_MB", 2048, 256),
CPUs: envFloat("ARTEX_SANDBOX_CPUS", 2.0, 0.25),
PidsLimit: envInt("ARTEX_SANDBOX_PIDS_LIMIT", 256, 32),
ShmSizeMB: envInt("ARTEX_SANDBOX_SHM_MB", 512, 64),
TmpSizeMB: envInt("ARTEX_SANDBOX_TMP_MB", 512, 64),
User: user,
AutoStopOnComplete: envBool("ARTEX_SANDBOX_AUTO_STOP", true),
SessionIdleMinutes: envInt("ARTEX_SANDBOX_SESSION_IDLE_MIN", 20, 1),
InstanceID: instanceID,
}
}
func envInt(key string, def, min int) int {
raw := strings.TrimSpace(os.Getenv(key))
if raw == "" {
return def
}
v, err := strconv.Atoi(raw)
if err != nil || v < min {
return def
}
return v
}
func envFloat(key string, def, min float64) float64 {
raw := strings.TrimSpace(os.Getenv(key))
if raw == "" {
return def
}
v, err := strconv.ParseFloat(raw, 64)
if err != nil || v < min {
return def
}
return v
}
func envBool(key string, def bool) bool {
raw := strings.ToLower(strings.TrimSpace(os.Getenv(key)))
switch raw {
case "1", "true", "yes", "on":
return true
case "0", "false", "no", "off":
return false
default:
return def
}
}
// ContainerInfo describes one sandbox container for API/UI reporting.
type ContainerInfo struct {
Scope Scope `json:"scope"`
OwnerID string `json:"owner_id"`
OwnerTitle string `json:"owner_title,omitempty"`
TaskRunning bool `json:"task_running,omitempty"`
Name string `json:"name"`
ContainerID string `json:"container_id,omitempty"`
ShortID string `json:"short_id,omitempty"`
Image string `json:"image"`
State string `json:"state"` // running | exited | created | missing | local | error
StatusText string `json:"status_text,omitempty"`
CreatedAt string `json:"created_at,omitempty"`
StartedAt string `json:"started_at,omitempty"`
ActiveRuns int `json:"active_runs"`
CPUPercent float64 `json:"cpu_percent,omitempty"`
MemUsageBytes uint64 `json:"mem_usage_bytes,omitempty"`
MemLimitBytes uint64 `json:"mem_limit_bytes,omitempty"`
PidsCurrent uint64 `json:"pids_current,omitempty"`
WorkDirContainer string `json:"work_dir_container"`
Network string `json:"network,omitempty"`
Runtime string `json:"runtime,omitempty"`
Error string `json:"error,omitempty"`
}
// GlobalStatus is returned by GET /api/sandbox/status.
type GlobalStatus struct {
Mode Mode `json:"mode"`
Enabled bool `json:"enabled"`
Available bool `json:"available"`
Error string `json:"error,omitempty"`
Image string `json:"image"`
Network string `json:"network"`
Runtime string `json:"runtime"`
MemoryMB int `json:"memory_mb"`
CPUs float64 `json:"cpus"`
PidsLimit int `json:"pids_limit"`
ShmSizeMB int `json:"shm_size_mb"`
AutoStopOnComplete bool `json:"auto_stop_on_complete"`
SessionIdleMinutes int `json:"session_idle_minutes"`
Containers []ContainerInfo `json:"containers"`
}
// ExecSpec describes one command invocation inside a sandbox container.
type ExecSpec struct {
Cmd []string
WorkDir string // container path; defaults to ContainerWorkDir
Env []string
Stdin []byte
Timeout time.Duration
MaxOutput int
KillOnAbort bool // wrap with PGID tracking so cancel/timeout kills child tree
}
// ExecResult captures the result of a foreground sandbox Exec.
type ExecResult struct {
Output string
OutputTruncated bool
ExitCode int
TimedOut bool
Err error
}
// StreamSession represents a live bidirectional stdio exec inside a sandbox.
type StreamSession struct {
Stdin io.WriteCloser
Stdout io.ReadCloser
Stderr io.ReadCloser
waitFn func() (int, error)
closeFn func() error
}
func (s *StreamSession) Wait() (int, error) {
if s == nil || s.waitFn == nil {
return 0, nil
}
return s.waitFn()
}
func (s *StreamSession) Close() error {
if s == nil || s.closeFn == nil {
return nil
}
return s.closeFn()
}
type targetCtxKey struct{}
// WithTarget attaches a sandbox Target to ctx.
func WithTarget(ctx context.Context, t Target) context.Context {
if !t.Valid() {
return ctx
}
return context.WithValue(ctx, targetCtxKey{}, t)
}
// TargetFrom extracts the sandbox Target from ctx, if present.
func TargetFrom(ctx context.Context) (Target, bool) {
if ctx == nil {
return Target{}, false
}
t, ok := ctx.Value(targetCtxKey{}).(Target)
if !ok || !t.Valid() {
return Target{}, false
}
return t, true
}
// ContainerName returns a deterministic, Docker-safe container name for target.
func (c Config) ContainerName(t Target) string {
cleanID := sanitizeToken(t.OwnerID)
return fmt.Sprintf("artex-sbx-%s-%s-%s", c.InstanceID, string(t.Scope), cleanID)
}
func sanitizeToken(s string) string {
var b strings.Builder
for _, r := range strings.ToLower(strings.TrimSpace(s)) {
if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '-' || r == '_' {
b.WriteRune(r)
} else {
b.WriteByte('-')
}
}
out := strings.Trim(b.String(), "-")
if out == "" {
return "0"
}
if len(out) > 48 {
out = out[:48]
}
return out
}
+163 -9
View File
@@ -3,25 +3,31 @@ package toolguard
import (
"context"
"fmt"
"io"
"os"
"os/exec"
"os/signal"
"runtime"
"strconv"
"strings"
"sync"
"syscall"
"time"
"github.com/Autumn-27/artex/internal/sandbox"
actool "github.com/Autumn-27/norma/tool"
)
const (
backgroundArg = "--artex-internal-background-tool"
backgroundExe = "_ARTEX_BG_EXE"
backgroundCommand = "_ARTEX_BG_COMMAND"
backgroundTimeout = "_ARTEX_BG_TIMEOUT"
backgroundCgroup = "_ARTEX_BG_CGROUP"
outputLimitNote = "\n\n[output truncated at capture limit]"
backgroundArg = "--artex-internal-background-tool"
backgroundExe = "_ARTEX_BG_EXE"
backgroundCommand = "_ARTEX_BG_COMMAND"
backgroundTimeout = "_ARTEX_BG_TIMEOUT"
backgroundCgroup = "_ARTEX_BG_CGROUP"
backgroundSandboxScope = "_ARTEX_BG_SANDBOX_SCOPE"
backgroundSandboxOwner = "_ARTEX_BG_SANDBOX_OWNER"
backgroundSandboxWorkDir = "_ARTEX_BG_SANDBOX_WORKDIR"
outputLimitNote = "\n\n[output truncated at capture limit]"
)
// The SDK's task manager only accepts a shell command, not an exec hook. Its
// shell execs this binary in a lightweight helper mode, keeping the manager's
// task ID, streaming output, notifications, and cancellation semantics.
@@ -89,7 +95,13 @@ func BackgroundHelper(args []string) (exitCode int, handled bool) {
}
command, dir := os.Getenv(backgroundCommand), os.Getenv(backgroundCgroup)
timeout, err := time.ParseDuration(os.Getenv(backgroundTimeout))
for _, name := range []string{backgroundExe, backgroundCommand, backgroundTimeout, backgroundCgroup} {
sbScope := os.Getenv(backgroundSandboxScope)
sbOwner := os.Getenv(backgroundSandboxOwner)
sbWorkDir := os.Getenv(backgroundSandboxWorkDir)
for _, name := range []string{
backgroundExe, backgroundCommand, backgroundTimeout, backgroundCgroup,
backgroundSandboxScope, backgroundSandboxOwner, backgroundSandboxWorkDir,
} {
_ = os.Unsetenv(name)
}
if command == "" || err != nil || timeout <= 0 {
@@ -98,6 +110,9 @@ func BackgroundHelper(args []string) (exitCode int, handled bool) {
}
cfg := FromEnv()
cfg.MaxOutputBytes -= 4096 // leave room for the error note below norma's task-file cap
if sbScope != "" && sbOwner != "" {
return runBackgroundHelperSandbox(cfg, sandbox.Target{Scope: sandbox.Scope(sbScope), OwnerID: sbOwner}, sbWorkDir, command, timeout), true
}
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
shell, flags := platformShellCmd()
@@ -124,3 +139,142 @@ func BackgroundHelper(args []string) (exitCode int, handled bool) {
return 1, true
}
}
func runGuardedBashBackgroundSandbox(tc *actool.ToolContext, mgr *sandbox.Manager, target sandbox.Target, containerWorkDir string, cfg Config, command string, timeout time.Duration) (actool.Result, error) {
exe, err := os.Executable()
if err != nil {
return actool.Errorf("Error: failed to locate background helper: " + err.Error()), nil
}
sbCfg := mgr.Config()
env := append([]string{}, tc.Env...)
env = append(env,
backgroundExe+"="+exe,
backgroundCommand+"="+command,
backgroundTimeout+"="+timeout.String(),
backgroundSandboxScope+"="+string(target.Scope),
backgroundSandboxOwner+"="+target.OwnerID,
backgroundSandboxWorkDir+"="+containerWorkDir,
"ARTEX_SANDBOX_MODE=docker",
"ARTEX_DOCKER_HOST="+sbCfg.DockerHost,
"ARTEX_SANDBOX_IMAGE="+sbCfg.Image,
"ARTEX_SANDBOX_NETWORK="+sbCfg.Network,
"ARTEX_SANDBOX_RUNTIME="+sbCfg.Runtime,
"ARTEX_SANDBOX_USER="+sbCfg.User,
"ARTEX_SANDBOX_INSTANCE="+sbCfg.InstanceID,
"ARTEX_HOST_DATA_DIR="+sbCfg.HostDataDir,
"_ARTEX_BG_DATA_DIR="+sbCfg.DataDir,
EnvToolMemoryLimitMB+"="+strconv.Itoa(cfg.MemoryLimitMB),
EnvToolPidsLimit+"="+strconv.Itoa(cfg.PidsLimit),
)
trampoline := `exec "$` + backgroundExe + `" ` + backgroundArg
if runtime.GOOS == "windows" {
trampoline = `& $env:` + backgroundExe + ` '` + backgroundArg + `'; exit $LASTEXITCODE`
}
desc := strings.TrimSpace(strings.ReplaceAll(command, "\n", " "))
if len(desc) > 60 {
desc = desc[:57] + "..."
}
mgrTasks := tc.Tasks
t, err := mgrTasks.Spawn(actool.SpawnSpec{
Command: trampoline, Kind: actool.KindBash, WorkingDir: tc.WorkingDir,
Description: desc, Env: env,
})
if err != nil {
return actool.Errorf("Error: failed to start background command: " + err.Error()), nil
}
mgrTasks.Background(t.ID)
return actool.Text(fmt.Sprintf(
"Running in background as %s. Output file: %s\nUse TaskOutput{task_id:%q} or Read to read its output; you are notified when it completes.",
t.ID, t.OutputPath, t.ID)), nil
}
func runBackgroundHelperSandbox(cfg Config, target sandbox.Target, workDir, command string, timeout time.Duration) int {
dataDir := os.Getenv("_ARTEX_BG_DATA_DIR")
_ = os.Unsetenv("_ARTEX_BG_DATA_DIR")
sbCfg := sandbox.ConfigFromEnv(dataDir, "")
mgr, err := sandbox.New(sbCfg)
if err != nil {
fmt.Fprintf(os.Stderr, "[sandbox init failed: %v]\n", err)
return 1
}
sigCtx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
ctx, cancel := context.WithTimeout(sigCtx, timeout)
defer cancel()
// Pass proxy env vars only (avoid leaking host env vars into container).
var passEnv []string
for _, k := range []string{"HTTP_PROXY", "HTTPS_PROXY", "http_proxy", "https_proxy", "ALL_PROXY", "all_proxy", "NODE_USE_ENV_PROXY", "SSL_CERT_FILE", "CURL_CA_BUNDLE", "REQUESTS_CA_BUNDLE", "GIT_SSL_CAINFO", "NODE_EXTRA_CA_CERTS"} {
if v := os.Getenv(k); v != "" {
passEnv = append(passEnv, k+"="+v)
}
}
stream, err := mgr.ExecStream(ctx, target, sandbox.ExecSpec{
Cmd: []string{"bash", "-c", command},
WorkDir: workDir,
Env: passEnv,
})
if err != nil {
fmt.Fprintf(os.Stderr, "[sandbox exec failed: %v]\n", err)
return 1
}
var outMu sync.Mutex
written := 0
truncated := false
writeCapped := func(r io.Reader) {
buf := make([]byte, 16*1024)
for {
n, rerr := r.Read(buf)
if n > 0 {
outMu.Lock()
if cfg.MaxOutputBytes > 0 && written >= cfg.MaxOutputBytes {
truncated = true
} else {
chunk := buf[:n]
if cfg.MaxOutputBytes > 0 && written+len(chunk) > cfg.MaxOutputBytes {
chunk = chunk[:cfg.MaxOutputBytes-written]
truncated = true
}
_, _ = os.Stdout.Write(chunk)
written += len(chunk)
}
outMu.Unlock()
}
if rerr != nil {
return
}
}
}
var wg sync.WaitGroup
wg.Add(2)
go func() { defer wg.Done(); writeCapped(stream.Stdout) }()
go func() { defer wg.Done(); writeCapped(stream.Stderr) }()
doneCh := make(chan int, 1)
go func() {
code, _ := stream.Wait()
wg.Wait()
doneCh <- code
}()
select {
case code := <-doneCh:
if truncated {
fmt.Fprintln(os.Stderr, outputLimitNote)
}
if code < 0 {
return 1
}
return code
case <-ctx.Done():
_ = stream.Close()
select {
case <-doneCh:
case <-time.After(3 * time.Second):
}
if ctx.Err() == context.DeadlineExceeded {
fmt.Fprintln(os.Stderr, timeoutNote(timeout))
}
return 1
}
}
+60
View File
@@ -11,6 +11,7 @@ import (
"strings"
"time"
"github.com/Autumn-27/artex/internal/sandbox"
"github.com/Autumn-27/norma/permission"
actool "github.com/Autumn-27/norma/tool"
)
@@ -57,6 +58,9 @@ func runGuardedBash(ctx context.Context, input json.RawMessage, tc *actool.ToolC
}
cfg := FromEnv()
timeout := cfg.ResolveTimeout(in.TimeoutMS)
if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() {
return runGuardedBashSandbox(ctx, mgr, tc, cfg, in.Command, timeout, in.RunInBackground)
}
if in.RunInBackground && tc != nil && tc.Tasks != nil && !actool.BackgroundTasksDisabled() {
return runGuardedBashBackground(tc, cfg, in.Command, timeout)
}
@@ -122,3 +126,59 @@ func mergedEnv(extra []string) []string {
func timeoutNote(limit time.Duration) string {
return fmt.Sprintf("\n\n[command timed out (configured limit %s)]", limit)
}
func runGuardedBashSandbox(ctx context.Context, mgr *sandbox.Manager, tc *actool.ToolContext, cfg Config, command string, timeout time.Duration, background bool) (actool.Result, error) {
target, ok := sandbox.TargetFrom(ctx)
ephemeral := false
if !ok {
target = sandbox.Target{Scope: sandbox.ScopeEphemeral, OwnerID: fmt.Sprintf("bash-%d", time.Now().UnixNano())}
ephemeral = true
defer func() {
rctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_ = mgr.Remove(rctx, target)
}()
}
containerWorkDir := sandbox.ContainerWorkDir
if tc != nil && tc.WorkingDir != "" {
containerWorkDir = sandbox.HostToContainerPath(mgr.Config().LocalRootFor(target), tc.WorkingDir)
}
if background && !ephemeral && tc != nil && tc.Tasks != nil && !actool.BackgroundTasksDisabled() {
return runGuardedBashBackgroundSandbox(tc, mgr, target, containerWorkDir, cfg, command, timeout)
}
var extraEnv []string
if tc != nil && len(tc.Env) > 0 {
extraEnv = append(extraEnv, tc.Env...)
}
res := mgr.Exec(ctx, target, sandbox.ExecSpec{
Cmd: []string{"bash", "-c", command},
WorkDir: containerWorkDir,
Env: extraEnv,
Timeout: timeout,
MaxOutput: cfg.MaxOutputBytes,
KillOnAbort: true,
})
out := actool.Capture(tc, res.Output)
if res.OutputTruncated {
out += outputLimitNote
}
if res.TimedOut {
return actool.Errorf(out + timeoutNote(timeout)), nil
}
if ctx.Err() != nil {
return actool.Errorf("Error: " + ctx.Err().Error()), nil
}
if res.Err != nil {
if res.ExitCode >= 0 {
if strings.TrimSpace(out) == "" {
out = "(no output)"
}
return actool.Errorf(fmt.Sprintf("%s\n\n[exit code %d]", out, res.ExitCode)), nil
}
return actool.Errorf(fmt.Sprintf("%s\n\n[failed to run in sandbox: %v]", out, res.Err)), nil
}
if strings.TrimSpace(out) == "" {
out = "(command produced no output)"
}
return actool.Text(out), nil
}
+53
View File
@@ -0,0 +1,53 @@
#!/bin/sh
# Close the host paths a sandbox container can use to reach ARTEX itself.
# The recording proxy already refuses loopback, metadata, postgres and the
# admin port. This script covers traffic that never enters the proxy:
# - packets from the sandbox bridge to the host's published :8787
# - packets routed from the sandbox bridge into the compose internal network
# (postgres, docker-socket-proxy, the ARTEX container)
# - packets toward the cloud metadata address
#
# Run on the Docker host after the networks exist. Safe to repeat.
set -eu
sandbox_net="${ARTEX_SANDBOX_NETWORK:-artex-sandbox}"
bridge_for() {
id=$(docker network inspect "$1" --format '{{.Id}}')
printf 'br-%.12s\n' "$id"
}
ensure() {
chain=$1
shift
if iptables -C "$chain" "$@" 2>/dev/null; then
return 0
fi
iptables -I "$chain" "$@"
}
if ! docker network inspect "$sandbox_net" >/dev/null 2>&1; then
echo "sandbox network $sandbox_net not found" >&2
exit 1
fi
sandbox_br=$(bridge_for "$sandbox_net")
ensure INPUT -i "$sandbox_br" -p tcp --dport 8787 -j REJECT
# Compose prefixes the internal network with the project name.
internal_net=$(docker network ls --format '{{.Name}}' | awk '/artex-internal$/ {print; exit}')
if [ -n "$internal_net" ]; then
internal_cidr=$(docker network inspect "$internal_net" --format '{{(index .IPAM.Config 0).Subnet}}')
if [ -n "$internal_cidr" ]; then
# Published :8788 is DNATed onto the ARTEX container, which lives in this
# subnet. Let only that port through, then refuse postgres, the Docker
# socket proxy, and the admin port.
ensure DOCKER-USER -i "$sandbox_br" -d "$internal_cidr" -j REJECT
ensure DOCKER-USER -i "$sandbox_br" -d "$internal_cidr" -p tcp --dport 8788 -j RETURN
fi
fi
ensure DOCKER-USER -i "$sandbox_br" -d 169.254.169.254/32 -j REJECT
echo "sandbox firewall applied on $sandbox_br"
+48 -5
View File
@@ -16,6 +16,7 @@ import (
"github.com/Autumn-27/artex/agent"
"github.com/Autumn-27/artex/db"
"github.com/Autumn-27/artex/intercept"
"github.com/Autumn-27/artex/internal/sandbox"
"github.com/Autumn-27/artex/sidequestion"
"github.com/Autumn-27/norma/llm"
)
@@ -230,6 +231,13 @@ func (s *Server) pgDeleteConversation(w http.ResponseWriter, r *http.Request) {
writeErr(w, 500, err.Error())
return
}
if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() {
go func(sessionID string) {
rctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
_ = mgr.Remove(rctx, sandbox.Target{Scope: sandbox.ScopeSession, OwnerID: sessionID})
}(s.convBusyKey(c.ID))
}
writeJSON(w, 200, map[string]any{"deleted": c.ID})
}
@@ -291,6 +299,16 @@ func (s *Server) pgDeleteConversationsBatch(w http.ResponseWriter, r *http.Reque
writeErr(w, http.StatusInternalServerError, err.Error())
return
}
if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() && len(deleted) > 0 {
deletedCopy := append([]int64(nil), deleted...)
go func() {
rctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
for _, id := range deletedCopy {
_ = mgr.Remove(rctx, sandbox.Target{Scope: sandbox.ScopeSession, OwnerID: s.convBusyKey(id)})
}
}()
}
deletedSet := make(map[int64]struct{}, len(deleted))
for _, id := range deleted {
deletedSet[id] = struct{}{}
@@ -512,11 +530,13 @@ func (s *Server) pgSendConversationMessage(w http.ResponseWriter, r *http.Reques
}
_ = pg.TouchConversation(c.ID)
// Append the uploaded files' ABSOLUTE paths so the ChatAgent opens them with its
// Read/Bash tools. baseDir = the agent's per-session CWD (<workDir>/sessions/
// conv-<id>/), matching chatUpload's landing dir and agent/chat.go's sessionWorkDir
// — busyKey == convBusyKey(c.ID) == "conv-<id>" == that session id.
// Append the uploaded files' paths so the ChatAgent opens them with its
// Read/Bash tools. In Docker sandbox mode the session directory is mounted
// at /workspace, so emit container paths (/workspace/uploads/...).
baseDir := filepath.Join(s.m.dir, "sessions", busyKey)
if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() {
baseDir = sandbox.ContainerWorkDir
}
s.runConversation(c, composeAgentMessage(agentMessage, req.Attachments, baseDir), busyKey, msg)
writeJSON(w, 202, map[string]any{"status": "accepted"})
}
@@ -549,8 +569,11 @@ func (s *Server) runConversation(c *db.Conversation, msg, busyKey string, userMe
// run ends (clearing busyKey). runConversation wraps it in a goroutine for the
// fire-and-forget chat path; the P3 trigger queue calls it directly so it can wait
// for completion before starting the next queued fire for the same agent.
func (s *Server) runConversationSync(c *db.Conversation, msg, busyKey string) {
func (s *Server) runConversationSync(c *db.Conversation, msg, busyKey string, presetTarget ...sandbox.Target) {
ctx, cancel := s.conversationRunContext(c.ID, busyKey)
if len(presetTarget) > 0 && presetTarget[0].Valid() {
ctx = sandbox.WithTarget(ctx, presetTarget[0])
}
s.runConversationTurn(ctx, cancel, c, msg, busyKey)
}
@@ -918,6 +941,7 @@ func mergeAllRuns(items []triggeredRun) triggeredRun {
message: b.String(),
taskID: first.taskID,
mergeable: true,
multiTask: len(order) > 1,
// taskDesc/taskGoal left empty: per-task headers already embedded above.
}
}
@@ -958,7 +982,26 @@ func (s *Server) runTriggeredRun(item triggeredRun) {
s.chatMu.Lock()
s.chatBusy[busyKey] = true
s.chatMu.Unlock()
var preset sandbox.Target
if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() {
if item.agentKey == "reporter" && item.taskID > 0 && !item.multiTask {
preset = sandbox.Target{Scope: sandbox.ScopeTask, OwnerID: strconv.FormatInt(item.taskID, 10)}
}
}
if preset.Valid() {
s.runConversationSync(c, msg, busyKey, preset)
if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() {
if t, ok := s.m.Task(preset.OwnerID); !ok || s.resolvedTaskStatus(t) != "running" {
mgr.RequestIdleStop(preset)
}
}
return
}
s.runConversationSync(c, msg, busyKey)
// Triggered one-shot sessions (no bound task) do not need to sit idle for 20m.
if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() {
mgr.RequestIdleStop(sandbox.Target{Scope: sandbox.ScopeSession, OwnerID: busyKey})
}
}
// firstLine returns a single-line, length-capped preview (shared with summaries).
+91 -5
View File
@@ -20,6 +20,7 @@ import (
"github.com/Autumn-27/artex/db"
"github.com/Autumn-27/artex/internal/httpidentity"
"github.com/Autumn-27/artex/internal/sandbox"
"github.com/Autumn-27/artex/internal/toolguard"
"github.com/Autumn-27/norma/permission"
actool "github.com/Autumn-27/norma/tool"
@@ -163,6 +164,18 @@ func (s *Server) pgTestCustomTool(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Minute)
defer cancel()
tc := &actool.ToolContext{WorkingDir: s.m.dir} // run in the project dir, like a real call
if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() && (req.Kind == "command" || req.Kind == "script") {
ephemeralTarget := sandbox.Target{Scope: sandbox.ScopeEphemeral, OwnerID: fmt.Sprintf("dryrun-%d", time.Now().UnixNano())}
ctx = sandbox.WithTarget(ctx, ephemeralTarget)
tc.WorkingDir = mgr.Config().LocalRootFor(ephemeralTarget)
tc.Env = mgr.ProxyEnv(s.m.traffic != nil)
defer func() {
rctx, rcancel := context.WithTimeout(context.Background(), 10*time.Second)
defer rcancel()
_ = mgr.Remove(rctx, ephemeralTarget)
_ = os.RemoveAll(mgr.Config().LocalRootFor(ephemeralTarget))
}()
}
var res actool.Result
switch req.Kind {
case "command":
@@ -356,10 +369,6 @@ func (s *Server) runScriptTool(ctx context.Context, key string, execRaw json.Raw
if strings.TrimSpace(spec.Code) == "" {
return actool.Errorf("script code 为空"), nil
}
interp := s.pythonInterpreter()
if interp == "" {
return actool.Errorf("未配置且未检测到 python 解释器(在系统配置里设置)"), nil
}
workDir := s.m.dir
var sessionEnv []string
if tc != nil {
@@ -368,7 +377,20 @@ func (s *Server) runScriptTool(ctx context.Context, key string, execRaw json.Raw
}
sessionEnv = tc.Env
}
body, err := execPython(ctx, interp, key, spec.Code, params, workDir, sessionEnv, toolguard.FromEnv().ResolveTimeout(spec.TimeoutMs))
timeout := toolguard.FromEnv().ResolveTimeout(spec.TimeoutMs)
var (
body string
err error
)
if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() {
body, err = execPythonSandbox(ctx, mgr, key, spec.Code, params, workDir, sessionEnv, timeout)
} else {
interp := s.pythonInterpreter()
if interp == "" {
return actool.Errorf("未配置且未检测到 python 解释器(在系统配置里设置)"), nil
}
body, err = execPython(ctx, interp, key, spec.Code, params, workDir, sessionEnv, timeout)
}
if err != nil {
out := actool.Capture(tc, body)
if out != "" {
@@ -428,6 +450,70 @@ func execPython(ctx context.Context, interp, key, code string, params map[string
return body, nil
}
func execPythonSandbox(ctx context.Context, mgr *sandbox.Manager, key, code string, params map[string]any, workDir string, sessionEnv []string, timeout time.Duration) (string, error) {
target, ok := sandbox.TargetFrom(ctx)
if !ok {
target = sandbox.Target{Scope: sandbox.ScopeEphemeral, OwnerID: fmt.Sprintf("script-%d", time.Now().UnixNano())}
defer func() {
rctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_ = mgr.Remove(rctx, target)
_ = os.RemoveAll(mgr.Config().LocalRootFor(target))
}()
}
hostRoot := mgr.Config().LocalRootFor(target)
if _, within := sandbox.CheckPathWithinRoot(hostRoot, workDir); !within {
workDir = hostRoot
}
toolsDir := filepath.Join(workDir, ".tools")
if err := os.MkdirAll(toolsDir, 0o777); err != nil {
return "", err
}
f, err := os.CreateTemp(toolsDir, key+"-*.py")
if err != nil {
return "", err
}
tmp := f.Name()
defer os.Remove(tmp)
if _, err := f.WriteString(code); err != nil {
f.Close()
return "", err
}
f.Close()
_ = os.Chmod(tmp, 0o644)
env := append([]string{}, sessionEnv...)
for k, v := range params {
if sv, ok := scalarStr(v); ok {
env = append(env, "TOOL_"+strings.ToUpper(k)+"="+sv)
}
}
pj, _ := json.Marshal(params)
containerWorkDir := sandbox.HostToContainerPath(hostRoot, workDir)
containerScript := sandbox.HostToContainerPath(hostRoot, tmp)
res := mgr.Exec(ctx, target, sandbox.ExecSpec{
Cmd: []string{"python3", containerScript},
WorkDir: containerWorkDir,
Env: env,
Stdin: pj,
Timeout: timeout,
MaxOutput: toolguard.FromEnv().MaxOutputBytes,
KillOnAbort: true,
})
body := res.Output
if res.OutputTruncated {
body += "\n\n[output truncated at capture limit]"
}
if res.TimedOut {
return body, fmt.Errorf("[command timed out (configured limit %s)]", timeout)
}
if res.Err != nil {
return body, fmt.Errorf("[exit: %w]", res.Err)
}
return body, nil
}
// ---------- http:原生请求 + 代理 ----------
func (s *Server) runHTTPTool(ctx context.Context, execRaw json.RawMessage, params map[string]any, tc *actool.ToolContext) (actool.Result, error) {
+17 -3
View File
@@ -14,6 +14,7 @@ import (
"github.com/Autumn-27/artex/agent"
"github.com/Autumn-27/artex/db"
"github.com/Autumn-27/artex/intercept"
"github.com/Autumn-27/artex/internal/sandbox"
"github.com/Autumn-27/norma/harness"
"github.com/Autumn-27/norma/llm"
"github.com/jackc/pgx/v5/pgconn"
@@ -190,6 +191,9 @@ func (e *Engine) nextPlannerRound(taskID string) int {
func (e *Engine) Pause(taskID string, cause error) {
e.paused.Store(taskID, true)
e.cancelExec(taskID, cause)
if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() {
mgr.RequestIdleStop(sandbox.Target{Scope: sandbox.ScopeTask, OwnerID: taskID})
}
}
// BeginDelete installs an execution barrier before task data/files are removed.
@@ -205,9 +209,13 @@ func (e *Engine) BeginDelete(taskID string) bool {
e.paused.Store(taskID, true)
e.deleteMu.Unlock()
e.cancelExec(taskID, agent.AbortTaskDeleted)
if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() {
sctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
_ = mgr.Stop(sctx, sandbox.Target{Scope: sandbox.ScopeTask, OwnerID: taskID})
cancel()
}
return true
}
func (e *Engine) AbortDelete(taskID string, keepPaused bool) {
e.deleteMu.Lock()
if !e.IsDeleting(taskID) {
@@ -306,11 +314,15 @@ func (e *Engine) StopTask(taskID string) {
}
return true
})
if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() {
rctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
_ = mgr.Remove(rctx, sandbox.Target{Scope: sandbox.ScopeTask, OwnerID: taskID})
cancel()
}
e.deleteMu.Lock()
e.deleting.Delete(taskID)
e.deleteMu.Unlock()
}
// cancelExec cancels a task's current per-task exec context (any in-flight
// planner.Plan / worker.Execute), if present. Shared by Pause and the settle
// sequence's hard-drain backstop.
@@ -336,10 +348,12 @@ func (e *Engine) Resume(t *Task) {
if e.IsDeleting(t.ID) {
return
}
if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() {
mgr.ClearIdleStop(sandbox.Target{Scope: sandbox.ScopeTask, OwnerID: t.ID})
}
e.paused.Delete(t.ID)
t.Notify()
}
// execContextFor returns a live per-task context derived from parent, recreating
// it if a prior pause cancelled it.
func (e *Engine) execContextFor(parent context.Context, taskID string) context.Context {
+14 -2
View File
@@ -21,6 +21,7 @@ import (
"github.com/Autumn-27/artex/enrich"
"github.com/Autumn-27/artex/guard"
"github.com/Autumn-27/artex/intercept"
"github.com/Autumn-27/artex/internal/sandbox"
"github.com/Autumn-27/artex/traffic"
actool "github.com/Autumn-27/norma/tool"
)
@@ -2052,12 +2053,16 @@ func (m *Manager) SetTaskStatusGuardedReason(id, status, reason string) (won boo
})
}
m.mu.Unlock()
if pgdb.IsTerminal(status) {
if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() {
mgr.RequestIdleStop(sandbox.Target{Scope: sandbox.ScopeTask, OwnerID: id})
}
}
if err := m.syncTaskRuntime(id, n); err != nil {
return true, err
}
return true, nil
}
// SetTaskStatus persists a task's lifecycle status (e.g. "done") and reflects it
// on the in-memory handle so the derived DTO status shows it without a reload.
func (m *Manager) SetTaskStatus(id, status string) error {
@@ -2097,12 +2102,19 @@ func (m *Manager) SetTaskStatus(id, status string) error {
})
}
m.mu.Unlock()
if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() {
target := sandbox.Target{Scope: sandbox.ScopeTask, OwnerID: id}
if pgdb.IsTerminal(status) {
mgr.RequestIdleStop(target)
} else {
mgr.ClearIdleStop(target)
}
}
if err := m.syncTaskRuntime(id, n); err != nil {
return err
}
return nil
}
// DeleteTask removes a task and optionally its related global data. Traffic has
// no task-id column, so related exchanges are resolved by exact hosts from the
// task's asset rows. Files are staged before the database operation; traffic is
+25 -1
View File
@@ -10,6 +10,7 @@ import (
"time"
"github.com/Autumn-27/artex/db"
"github.com/Autumn-27/artex/internal/sandbox"
"github.com/Autumn-27/artex/mcphttp"
actool "github.com/Autumn-27/norma/tool"
)
@@ -52,6 +53,16 @@ func resolveStdioMCPCommand(command string, args []string) (string, []string) {
if pkgIdx < 0 {
return command, out
}
if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() {
rest := make([]string, 0, len(out)-1)
for i, arg := range out {
if i == pkgIdx || (i < pkgIdx && (arg == "-y" || arg == "--yes")) {
continue
}
rest = append(rest, arg)
}
return "playwright-mcp", rest
}
if bin, err := lookPath("playwright-mcp"); err == nil && strings.TrimSpace(bin) != "" {
rest := make([]string, 0, len(out)-1)
for i, arg := range out {
@@ -97,7 +108,20 @@ func connectMCP(ctx context.Context, m *db.MCPServer, workDir string) (mcpClient
// discoverAndCacheMCP connects to one MCP, lists its tools, and persists the tool
// names to mcp_tools_cache so the UI shows them without a live connection.
func (s *Server) discoverAndCacheMCP(ctx context.Context, m *db.MCPServer) error {
cl, err := connectMCP(ctx, m, s.m.dir)
workDir := s.m.dir
if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() && m.Transport == "stdio" {
if _, hasTarget := sandbox.TargetFrom(ctx); !hasTarget {
ephemeral := sandbox.Target{Scope: sandbox.ScopeEphemeral, OwnerID: fmt.Sprintf("mcp-discover-%d", time.Now().UnixNano())}
ctx = sandbox.WithTarget(ctx, ephemeral)
workDir = mgr.Config().LocalRootFor(ephemeral)
defer func() {
rctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_ = mgr.Remove(rctx, ephemeral)
}()
}
}
cl, err := connectMCP(ctx, m, workDir)
if err != nil {
return err
}
+91 -5
View File
@@ -13,6 +13,7 @@ import (
"strings"
"sync"
"github.com/Autumn-27/artex/internal/sandbox"
"github.com/Autumn-27/norma/llm"
"github.com/Autumn-27/norma/mcp"
"github.com/Autumn-27/norma/permission"
@@ -93,14 +94,45 @@ type stdioMCPClient struct {
pending map[int]chan stdioRPCResponse
closeCh chan struct{}
once sync.Once
cmd *exec.Cmd
stdin io.Closer
stderr *tailBuffer
closeOnce sync.Once
cmd *exec.Cmd
stream *sandbox.StreamSession
stdin io.Closer
stderr *tailBuffer
releaseSlot func()
closeOnce sync.Once
}
const maxSandboxBrowserMCPPerTarget = 2
var (
sandboxBrowserSlotsMu sync.Mutex
sandboxBrowserSlots = map[string]chan struct{}{}
)
func acquireSandboxBrowserSlot(ctx context.Context, targetKey string) (func(), error) {
sandboxBrowserSlotsMu.Lock()
ch, ok := sandboxBrowserSlots[targetKey]
if !ok {
ch = make(chan struct{}, maxSandboxBrowserMCPPerTarget)
sandboxBrowserSlots[targetKey] = ch
}
sandboxBrowserSlotsMu.Unlock()
select {
case ch <- struct{}{}:
var once sync.Once
return func() {
once.Do(func() { <-ch })
}, nil
case <-ctx.Done():
return nil, ctx.Err()
}
}
func newStdioMCPClient(ctx context.Context, server, workDir, command string, env map[string]string, args ...string) (*stdioMCPClient, error) {
if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() {
if target, ok := sandbox.TargetFrom(ctx); ok {
return newSandboxStdioMCPClient(ctx, mgr, target, server, workDir, command, env, args...)
}
}
cmd := exec.Command(command, args...)
if strings.TrimSpace(workDir) != "" {
cmd.Dir = workDir
@@ -141,6 +173,54 @@ func newStdioMCPClient(ctx context.Context, server, workDir, command string, env
return c, nil
}
func newSandboxStdioMCPClient(ctx context.Context, mgr *sandbox.Manager, target sandbox.Target, server, workDir, command string, env map[string]string, args ...string) (*stdioMCPClient, error) {
var releaseSlot func()
if server == browserMCPName && target.Scope == sandbox.ScopeTask {
rel, err := acquireSandboxBrowserSlot(ctx, target.Key())
if err != nil {
return nil, fmt.Errorf("wait browser sandbox slot for %s: %w", target.Key(), err)
}
releaseSlot = rel
}
containerWorkDir := sandbox.ContainerWorkDir
if strings.TrimSpace(workDir) != "" {
containerWorkDir = sandbox.HostToContainerPath(mgr.Config().LocalRootFor(target), workDir)
}
envSlice := append([]string{}, mgr.ProxyEnv(true)...)
for k, v := range env {
envSlice = append(envSlice, k+"="+v)
}
stream, err := mgr.ExecStream(ctx, target, sandbox.ExecSpec{
Cmd: append([]string{command}, args...),
WorkDir: containerWorkDir,
Env: envSlice,
})
if err != nil {
if releaseSlot != nil {
releaseSlot()
}
return nil, err
}
stderr := newTailBuffer(4096)
go func() { _, _ = io.Copy(stderr, stream.Stderr) }()
c := &stdioMCPClient{
server: server,
w: stream.Stdin,
pending: map[int]chan stdioRPCResponse{},
closeCh: make(chan struct{}),
stream: stream,
stdin: stream.Stdin,
stderr: stderr,
releaseSlot: releaseSlot,
}
go c.readLoop(stream.Stdout)
if err := c.initialize(ctx); err != nil {
_ = c.Close()
return nil, err
}
return c, nil
}
func (c *stdioMCPClient) readLoop(r io.Reader) {
br := bufio.NewReaderSize(r, 64*1024)
for {
@@ -287,10 +367,16 @@ func (c *stdioMCPClient) Close() error {
if c.stdin != nil {
_ = c.stdin.Close()
}
if c.stream != nil {
_ = c.stream.Close()
}
if c.cmd != nil && c.cmd.Process != nil {
_ = c.cmd.Process.Kill()
_ = c.cmd.Wait()
}
if c.releaseSlot != nil {
c.releaseSlot()
}
})
return nil
}
+15 -3
View File
@@ -79,6 +79,7 @@ func (s *Server) orchestrationTools() []actool.CoreTool {
s.toolListWorkerTraces(),
s.toolSearchWorkerTraces(),
s.toolGetTaskNodeDetail(),
s.toolReadTaskFile(),
s.toolUpdateFindingReport(),
s.toolGetFindingTraffic(),
s.toolBindFindingTraffic(),
@@ -273,6 +274,7 @@ func (s *Server) toolSpawnTask() actool.CoreTool {
"timeout_seconds": map[string]any{"type": "integer", "description": "可选:任务级超时(秒)。到点后触发优雅收尾并进入 timeout 终态;留空或 0 = 不限时"},
"plan_heartbeat_seconds": map[string]any{"type": "integer", "description": "可选:planner 心跳触发间隔(秒)。距上轮规划结束/任务开始满该值且期间无触发 → 触发一轮规划(兜底死锁 + 唤醒去监督飞行中的 worker)。留空或 0 = 默认 600(10min);"},
"seed_first_intent": map[string]any{"type": "boolean", "description": "可选:对于简单任务可开启,创建时直接下发一条种子意图(内容=描述+目标)让 worker 免等首轮 planner 直接开跑测试;默认 false(走标准先规划再执行)。"},
"attachments": map[string]any{"type": "array", "items": map[string]any{"type": "string"}, "description": "可选:要从当前对话工作区附带到新任务工作区(/workspace/uploads/)的文件路径列表,如 [\"uploads/targets.txt\"]。"},
}, "description", "goal"),
func(ctx context.Context, in json.RawMessage) (actool.Result, error) {
var a struct {
@@ -287,8 +289,8 @@ func (s *Server) toolSpawnTask() actool.CoreTool {
TimeoutSeconds int `json:"timeout_seconds"`
PlanHeartbeatSeconds int `json:"plan_heartbeat_seconds"`
SeedFirstIntent bool `json:"seed_first_intent"`
Attachments []string `json:"attachments"`
}
_ = json.Unmarshal(in, &a)
if strings.TrimSpace(a.Description) == "" {
a.Description = "未命名任务"
}
@@ -380,6 +382,16 @@ func (s *Server) toolSpawnTask() actool.CoreTool {
_ = s.m.PG().SetParentRef(id, a.ParentRef)
}
}
if sessID := agent.RunInfoFrom(ctx).SessionID; sessID != "" {
newDesc, newGoal, copied := transferSessionAttachmentsToTask(s.m.dir, sessID, t.ID, a.Attachments, a.Description, a.Goal)
if copied > 0 {
a.Description, a.Goal = newDesc, newGoal
t.Description, t.Goal = newDesc, newGoal
if id, e := strconv.ParseInt(t.ID, 10, 64); e == nil && s.m.pg != nil {
_, _ = s.m.pg.Exec(`UPDATE tasks SET description=$2, goal=$3 WHERE id=$1`, id, newDesc, newGoal)
}
}
}
// 共享的建后流程,与 HTTP 建任务(server.go createTask)复用同一段 launchTask:
// seed + 后台可见地做目标分解(第0轮/LLM步骤/逐条goal) + engine.Run。
// seed_first_intent 默认 false(标准先规划再执行);简单任务可开启直接下发一 work 测试。
@@ -1144,11 +1156,11 @@ func (s *Server) seedWorkerReadbackRebind() {
// before Auto existed still give Auto its default toolset — without re-adding it
// after a user deliberately unbinds.
func (s *Server) seedAutoDefaultBindings() {
const flag = "auto_default_bindings_v3" // v3: 替换旧资产工具名,加入 insert_assets/add_company_scope
const flag = "auto_default_bindings_v4" // v4: 加入 read_task_file 只读跨容器产物查看工具
if v, _, _ := s.m.pg.GetSetting(flag); v == "true" {
return
}
keys := make([]string, 0, len(platformToolKeys)+12)
keys := make([]string, 0, len(platformToolKeys)+13)
for _, t := range s.orchestrationTools() {
keys = append(keys, t.Name())
}
+490
View File
@@ -0,0 +1,490 @@
package server
import (
"context"
"encoding/json"
"log"
"net"
"net/http"
"net/url"
"os"
"strings"
"time"
"github.com/Autumn-27/artex/agent"
"github.com/Autumn-27/artex/internal/sandbox"
"github.com/Autumn-27/artex/traffic"
)
const settingSandboxOverrides = "sandbox_settings_json"
// initSandbox wires the global sandbox manager, applies persisted UI overrides,
// reconciles orphan containers on startup, starts the idle session reaper, and
// configures the recording proxy SSRF guard.
func (s *Server) initSandbox() {
caCert := ""
if s.m.traffic != nil {
caCert = s.m.traffic.CACertPath()
}
cfg := sandbox.ConfigFromEnv(s.dataDir, caCert)
mgr, err := sandbox.New(cfg)
if err != nil {
log.Printf("[sandbox] init failed (falling back to local): %v", err)
cfg.Mode = sandbox.ModeLocal
mgr, _ = sandbox.New(cfg)
}
if s.m.pg != nil {
if raw, ok, _ := s.m.pg.GetSetting(settingSandboxOverrides); ok && strings.TrimSpace(raw) != "" {
var ov sandbox.RuntimeOverrides
if json.Unmarshal([]byte(raw), &ov) == nil {
mgr.ApplyOverrides(ov)
}
}
}
sandbox.SetDefault(mgr)
if !mgr.Enabled() {
log.Printf("[sandbox] mode=local (set ARTEX_SANDBOX_MODE=docker to enable container isolation)")
return
}
validTasks := map[string]bool{}
for _, t := range s.m.List() {
validTasks[t.ID] = true
}
var validSessions map[string]bool
if s.m.pg != nil {
if convs, err := s.m.pg.ListConversations(); err == nil {
validSessions = make(map[string]bool, len(convs))
for _, c := range convs {
validSessions[s.convBusyKey(c.ID)] = true
}
}
}
rctx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
defer cancel()
if err := mgr.ReconcileOnStartup(rctx, validTasks, validSessions); err != nil {
log.Printf("[sandbox] startup reconcile warning: %v", err)
} else {
log.Printf("[sandbox] mode=docker image=%s network=%s runtime=%q mem=%dMiB cpus=%.2f",
mgr.Config().Image, mgr.Config().Network, mgr.Config().Runtime, mgr.Config().MemoryMB, mgr.Config().CPUs)
}
mgr.StartBackgroundReaper(s.ctx)
// Enable SSRF guard on the recording proxy so sandbox containers cannot pivot
// through :8788 to reach :8787, postgres, docker-socket-proxy, or cloud metadata.
if s.m.traffic != nil {
blockedHosts := []string{"artex", "postgres", "docker-socket-proxy"}
if pgHost := parsePGHostFromEnv(); pgHost != "" {
blockedHosts = append(blockedHosts, pgHost)
}
blockPrivate := strings.EqualFold(strings.TrimSpace(os.Getenv("ARTEX_PROXY_BLOCK_PRIVATE")), "true") ||
strings.TrimSpace(os.Getenv("ARTEX_PROXY_BLOCK_PRIVATE")) == "1"
s.m.traffic.EnableSSRFGuard(traffic.SSRFGuardConfig{
Enabled: true,
BlockPrivate: blockPrivate,
BlockedHosts: blockedHosts,
BlockedCIDRs: mgr.SandboxSubnets(),
InfraIPs: parseProtectIPs(os.Getenv("ARTEX_PROXY_PROTECT_IPS")),
})
}
}
func parseProtectIPs(raw string) []net.IP {
var out []net.IP
for _, part := range strings.FieldsFunc(raw, func(r rune) bool {
return r == ',' || r == ';' || r == ' ' || r == '\n' || r == '\t'
}) {
if ip := net.ParseIP(strings.TrimSpace(part)); ip != nil {
out = append(out, ip)
}
}
return out
}
func parsePGHostFromEnv() string {
dsn := strings.TrimSpace(os.Getenv("ARTEX_PG_DSN"))
if dsn == "" {
return ""
}
if u, err := url.Parse(dsn); err == nil && u.Hostname() != "" {
return u.Hostname()
}
return ""
}
// blockSandboxAdminAccess rejects HTTP requests to :8787 coming from inside the
// isolated sandbox Docker network.
func (s *Server) blockSandboxAdminAccess(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if mgr := sandbox.Default(); mgr != nil && mgr.IsSandboxSourceIP(r.RemoteAddr) {
http.Error(w, "forbidden: sandbox container cannot access ARTEX management API", http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
})
}
func (s *Server) enrichSandboxContainer(ci *sandbox.ContainerInfo) {
if ci == nil {
return
}
if ci.Scope == sandbox.ScopeTask {
if t, ok := s.m.Task(ci.OwnerID); ok {
title := strings.TrimSpace(t.Name)
if title == "" {
title = strings.TrimSpace(t.Description)
}
ci.OwnerTitle = title
ci.TaskRunning = s.resolvedTaskStatus(t) == "running"
}
}
}
// GET /api/sandbox/status
func (s *Server) sandboxStatus(w http.ResponseWriter, r *http.Request) {
mgr := sandbox.Default()
if mgr == nil {
writeJSON(w, 200, sandbox.GlobalStatus{Mode: sandbox.ModeLocal, Available: true, Containers: []sandbox.ContainerInfo{}})
return
}
withStats := r.URL.Query().Get("stats") == "1"
ctx, cancel := context.WithTimeout(r.Context(), 12*time.Second)
defer cancel()
st := mgr.StatusWithStats(ctx, withStats)
for i := range st.Containers {
s.enrichSandboxContainer(&st.Containers[i])
}
writeJSON(w, 200, st)
}
// PUT /api/sandbox/settings
func (s *Server) updateSandboxSettings(w http.ResponseWriter, r *http.Request) {
var ov sandbox.RuntimeOverrides
if err := json.NewDecoder(r.Body).Decode(&ov); err != nil {
writeErr(w, 400, "bad json: "+err.Error())
return
}
if ov.MemoryMB != nil && (*ov.MemoryMB < 256 || *ov.MemoryMB > 65536) {
writeErr(w, 400, "内存上限必须在 256 到 65536 MiB 之间")
return
}
if ov.CPUs != nil && (*ov.CPUs < 0.25 || *ov.CPUs > 64) {
writeErr(w, 400, "CPU 上限必须在 0.25 到 64 之间")
return
}
if ov.PidsLimit != nil && (*ov.PidsLimit < 32 || *ov.PidsLimit > 8192) {
writeErr(w, 400, "进程数上限必须在 32 到 8192 之间")
return
}
if ov.ShmSizeMB != nil && (*ov.ShmSizeMB < 64 || *ov.ShmSizeMB > 8192) {
writeErr(w, 400, "共享内存上限必须在 64 到 8192 MiB 之间")
return
}
if ov.SessionIdleMinutes != nil && (*ov.SessionIdleMinutes < 1 || *ov.SessionIdleMinutes > 1440) {
writeErr(w, 400, "对话空闲停机时间必须在 1 到 1440 分钟之间")
return
}
if mgr := sandbox.Default(); mgr != nil {
mgr.ApplyOverrides(ov)
if s.m.pg != nil {
cfg := mgr.Config()
persisted := sandbox.RuntimeOverrides{
Image: &cfg.Image,
MemoryMB: &cfg.MemoryMB,
CPUs: &cfg.CPUs,
PidsLimit: &cfg.PidsLimit,
ShmSizeMB: &cfg.ShmSizeMB,
Runtime: &cfg.Runtime,
AutoStopOnComplete: &cfg.AutoStopOnComplete,
SessionIdleMinutes: &cfg.SessionIdleMinutes,
}
if b, err := json.Marshal(persisted); err == nil {
_ = s.m.pg.SetSetting(settingSandboxOverrides, string(b))
}
}
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
defer cancel()
writeJSON(w, 200, mgr.Status(ctx))
return
}
writeJSON(w, 200, sandbox.GlobalStatus{Mode: sandbox.ModeLocal, Available: true, Containers: []sandbox.ContainerInfo{}})
}
// POST /api/sandbox/prune
func (s *Server) pruneSandboxContainers(w http.ResponseWriter, r *http.Request) {
mgr := sandbox.Default()
if mgr == nil || !mgr.Enabled() {
writeJSON(w, 200, map[string]any{"removed": 0})
return
}
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
removed, err := mgr.PruneStopped(ctx)
if err != nil {
writeErr(w, 500, err.Error())
return
}
writeJSON(w, 200, map[string]any{"removed": removed})
}
// GET /api/sandbox/containers/{scope}/{id}
func (s *Server) getSandboxContainer(w http.ResponseWriter, r *http.Request) {
target := sandbox.Target{Scope: sandbox.Scope(r.PathValue("scope")), OwnerID: r.PathValue("id")}
if !target.Valid() || (target.Scope != sandbox.ScopeTask && target.Scope != sandbox.ScopeSession) {
writeErr(w, 400, "无效的沙箱目标")
return
}
mgr := sandbox.Default()
if mgr == nil || !mgr.Enabled() {
writeJSON(w, 200, sandbox.ContainerInfo{
Scope: target.Scope,
OwnerID: target.OwnerID,
State: "local",
WorkDirContainer: sandbox.ContainerWorkDir,
})
return
}
withStats := r.URL.Query().Get("stats") != "0"
ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second)
defer cancel()
info, _ := mgr.Inspect(ctx, target, withStats)
s.enrichSandboxContainer(&info)
writeJSON(w, 200, info)
}
// POST /api/sandbox/containers/{scope}/{id}/start
func (s *Server) startSandboxContainer(w http.ResponseWriter, r *http.Request) {
mgr := sandbox.Default()
if mgr == nil || !mgr.Enabled() {
writeErr(w, 400, "沙箱容器模式未开启")
return
}
target := sandbox.Target{Scope: sandbox.Scope(r.PathValue("scope")), OwnerID: r.PathValue("id")}
if !target.Valid() || (target.Scope != sandbox.ScopeTask && target.Scope != sandbox.ScopeSession) {
writeErr(w, 400, "无效的沙箱目标")
return
}
mgr.ClearIdleStop(target)
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
if _, err := mgr.Ensure(ctx, target); err != nil {
writeErr(w, 500, err.Error())
return
}
info, _ := mgr.Inspect(ctx, target, true)
s.enrichSandboxContainer(&info)
writeJSON(w, 200, info)
}
// POST /api/sandbox/containers/{scope}/{id}/recreate
func (s *Server) recreateSandboxContainer(w http.ResponseWriter, r *http.Request) {
mgr := sandbox.Default()
if mgr == nil || !mgr.Enabled() {
writeErr(w, 400, "沙箱容器模式未开启")
return
}
target := sandbox.Target{Scope: sandbox.Scope(r.PathValue("scope")), OwnerID: r.PathValue("id")}
if !target.Valid() || (target.Scope != sandbox.ScopeTask && target.Scope != sandbox.ScopeSession) {
writeErr(w, 400, "无效的沙箱目标")
return
}
var req struct {
PauseTask bool `json:"pause_task"`
ClearWorkspace bool `json:"clear_workspace"`
}
_ = json.NewDecoder(r.Body).Decode(&req)
if target.Scope == sandbox.ScopeTask {
if t, ok := s.m.Task(target.OwnerID); ok && s.resolvedTaskStatus(t) == "running" {
if !req.PauseTask {
writeErr(w, 409, "任务正在运行,请确认同时暂停任务后再重建容器")
return
}
_, _ = s.applyTaskControlWithCause(t, "pause", agent.AbortPausedByUser)
}
}
mgr.ClearIdleStop(target)
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
info, err := mgr.Recreate(ctx, target, req.ClearWorkspace)
if err != nil {
writeErr(w, 500, err.Error())
return
}
s.enrichSandboxContainer(&info)
writeJSON(w, 200, info)
}
// POST /api/sandbox/containers/{scope}/{id}/stop
func (s *Server) stopSandboxContainer(w http.ResponseWriter, r *http.Request) {
mgr := sandbox.Default()
if mgr == nil || !mgr.Enabled() {
writeErr(w, 400, "沙箱容器模式未开启")
return
}
target := sandbox.Target{Scope: sandbox.Scope(r.PathValue("scope")), OwnerID: r.PathValue("id")}
if !target.Valid() {
writeErr(w, 400, "无效的沙箱目标")
return
}
if target.Scope == sandbox.ScopeTask {
if t, ok := s.m.Task(target.OwnerID); ok && s.resolvedTaskStatus(t) == "running" {
_, _ = s.applyTaskControlWithCause(t, "pause", agent.AbortPausedByUser)
}
}
ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
defer cancel()
if err := mgr.Stop(ctx, target); err != nil {
writeErr(w, 500, err.Error())
return
}
info, _ := mgr.Inspect(ctx, target, false)
s.enrichSandboxContainer(&info)
writeJSON(w, 200, info)
}
// DELETE /api/sandbox/containers/{scope}/{id}
func (s *Server) removeSandboxContainer(w http.ResponseWriter, r *http.Request) {
mgr := sandbox.Default()
if mgr == nil || !mgr.Enabled() {
writeErr(w, 400, "沙箱容器模式未开启")
return
}
target := sandbox.Target{Scope: sandbox.Scope(r.PathValue("scope")), OwnerID: r.PathValue("id")}
if !target.Valid() {
writeErr(w, 400, "无效的沙箱目标")
return
}
if target.Scope == sandbox.ScopeTask {
if t, ok := s.m.Task(target.OwnerID); ok && s.resolvedTaskStatus(t) == "running" {
_, _ = s.applyTaskControlWithCause(t, "pause", agent.AbortPausedByUser)
}
}
ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
defer cancel()
if err := mgr.Remove(ctx, target); err != nil {
writeErr(w, 500, err.Error())
return
}
writeJSON(w, 200, map[string]any{"removed": target.Key()})
}
// GET /api/tasks/{id}/sandbox
func (s *Server) getTaskSandbox(w http.ResponseWriter, r *http.Request) {
t, ok := s.m.Task(r.PathValue("id"))
if !ok {
writeErr(w, 404, "task not found")
return
}
mgr := sandbox.Default()
target := sandbox.Target{Scope: sandbox.ScopeTask, OwnerID: t.ID}
if mgr == nil || !mgr.Enabled() {
writeJSON(w, 200, sandbox.ContainerInfo{
Scope: sandbox.ScopeTask,
OwnerID: t.ID,
State: "local",
WorkDirContainer: sandbox.ContainerWorkDir,
})
return
}
withStats := r.URL.Query().Get("stats") != "0"
ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second)
defer cancel()
info, _ := mgr.Inspect(ctx, target, withStats)
writeJSON(w, 200, info)
}
// POST /api/tasks/{id}/sandbox/start
func (s *Server) startTaskSandbox(w http.ResponseWriter, r *http.Request) {
t, ok := s.m.Task(r.PathValue("id"))
if !ok {
writeErr(w, 404, "task not found")
return
}
mgr := sandbox.Default()
if mgr == nil || !mgr.Enabled() {
writeErr(w, 400, "沙箱容器模式未开启")
return
}
target := sandbox.Target{Scope: sandbox.ScopeTask, OwnerID: t.ID}
mgr.ClearIdleStop(target)
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
if _, err := mgr.Ensure(ctx, target); err != nil {
writeErr(w, 500, err.Error())
return
}
info, _ := mgr.Inspect(ctx, target, true)
writeJSON(w, 200, info)
}
// POST /api/tasks/{id}/sandbox/stop
func (s *Server) stopTaskSandbox(w http.ResponseWriter, r *http.Request) {
t, ok := s.m.Task(r.PathValue("id"))
if !ok {
writeErr(w, 404, "task not found")
return
}
mgr := sandbox.Default()
if mgr == nil || !mgr.Enabled() {
writeErr(w, 400, "沙箱容器模式未开启")
return
}
var req struct {
PauseTask bool `json:"pause_task"`
}
_ = json.NewDecoder(r.Body).Decode(&req)
status := s.resolvedTaskStatus(t)
if status == "running" {
if !req.PauseTask {
writeErr(w, 409, "任务正在运行,请确认同时暂停任务后再停止容器")
return
}
_, _ = s.applyTaskControlWithCause(t, "pause", agent.AbortPausedByUser)
}
target := sandbox.Target{Scope: sandbox.ScopeTask, OwnerID: t.ID}
ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
defer cancel()
if err := mgr.Stop(ctx, target); err != nil {
writeErr(w, 500, err.Error())
return
}
info, _ := mgr.Inspect(ctx, target, false)
writeJSON(w, 200, info)
}
// POST /api/tasks/{id}/sandbox/recreate
func (s *Server) recreateTaskSandbox(w http.ResponseWriter, r *http.Request) {
t, ok := s.m.Task(r.PathValue("id"))
if !ok {
writeErr(w, 404, "task not found")
return
}
mgr := sandbox.Default()
if mgr == nil || !mgr.Enabled() {
writeErr(w, 400, "沙箱容器模式未开启")
return
}
var req struct {
PauseTask bool `json:"pause_task"`
ClearWorkspace bool `json:"clear_workspace"`
}
_ = json.NewDecoder(r.Body).Decode(&req)
if s.resolvedTaskStatus(t) == "running" {
if !req.PauseTask {
writeErr(w, 409, "任务正在运行,请确认同时暂停任务后再重建容器")
return
}
_, _ = s.applyTaskControlWithCause(t, "pause", agent.AbortPausedByUser)
}
target := sandbox.Target{Scope: sandbox.ScopeTask, OwnerID: t.ID}
mgr.ClearIdleStop(target)
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
info, err := mgr.Recreate(ctx, target, req.ClearWorkspace)
if err != nil {
writeErr(w, 500, err.Error())
return
}
writeJSON(w, 200, info)
}
+205
View File
@@ -0,0 +1,205 @@
package server
import (
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
"github.com/Autumn-27/artex/internal/sandbox"
actool "github.com/Autumn-27/norma/tool"
)
var (
reDraftUploadPath = regexp.MustCompile(`(?:[^\s"'\x60<>()]*?/)?drafts/([A-Za-z0-9_-]+)/uploads/([^\s"'\x60<>()(),,;;]+)`)
reSessionUploadPath = regexp.MustCompile(`(?:[^\s"'\x60<>()]*?/)?sessions/([A-Za-z0-9_-]+)/([^\s"'\x60<>()(),,;;]+)`)
reContainerFilePath = regexp.MustCompile(`/workspace/([^\s"'\x60<>()(),,;;]+)`)
)
// transferDraftUploadsToTask copies any pre-task staged uploads referenced in
// description/goal from <dataDir>/drafts/<draftID>/uploads/ into the newly
// created task's <dataDir>/tasks/<taskID>/uploads/ and rewrites their paths so
// sandboxed task containers can access them under /workspace/uploads/<file>.
func transferDraftUploadsToTask(dataDir, taskID, description, goal string) (string, string, int) {
if strings.TrimSpace(taskID) == "" {
return description, goal, 0
}
taskRoot := filepath.Join(dataDir, "tasks", taskID)
sandboxOn := sandbox.Default() != nil && sandbox.Default().Enabled()
copied := 0
rewritten := map[string]string{}
rewriteText := func(text string) string {
return reDraftUploadPath.ReplaceAllStringFunc(text, func(match string) string {
if prev, ok := rewritten[match]; ok {
return prev
}
sub := reDraftUploadPath.FindStringSubmatch(match)
if len(sub) != 3 {
return match
}
draftRoot := filepath.Join(dataDir, "drafts", sub[1])
relDst, err := sandbox.CopyRegularFileSafe(draftRoot, filepath.Join("uploads", sub[2]), taskRoot, "uploads")
if err != nil {
return match
}
copied++
var targetPath string
if sandboxOn {
targetPath = sandbox.ContainerWorkDir + "/" + relDst
} else {
targetPath = filepath.Join(taskRoot, filepath.FromSlash(relDst))
}
rewritten[match] = targetPath
return targetPath
})
}
return rewriteText(description), rewriteText(goal), copied
}
// transferSessionAttachmentsToTask copies attachments from an auto/chat session
// into a newly spawned task's uploads/ directory — handling both explicit
// attachments passed to spawn_task AND fallback path references in description/goal.
func transferSessionAttachmentsToTask(dataDir, sessionID, taskID string, explicit []string, description, goal string) (string, string, int) {
if strings.TrimSpace(taskID) == "" || strings.TrimSpace(sessionID) == "" {
return description, goal, 0
}
sessionRoot := filepath.Join(dataDir, "sessions", sessionID)
taskRoot := filepath.Join(dataDir, "tasks", taskID)
sandboxOn := sandbox.Default() != nil && sandbox.Default().Enabled()
formatTarget := func(relDst string) string {
if sandboxOn {
return sandbox.ContainerWorkDir + "/" + relDst
}
return filepath.Join(taskRoot, filepath.FromSlash(relDst))
}
copied := 0
copiedByRel := map[string]string{} // normalized session-relative path -> new target path
copyOne := func(candidate string) (string, bool) {
norm := strings.TrimSpace(candidate)
if norm == "" {
return "", false
}
if prev, ok := copiedByRel[norm]; ok {
return prev, true
}
relDst, err := sandbox.CopyRegularFileSafe(sessionRoot, norm, taskRoot, "uploads")
if err != nil {
return "", false
}
copied++
outPath := formatTarget(relDst)
copiedByRel[norm] = outPath
return outPath, true
}
var explicitManifest []string
for _, raw := range explicit {
if targetPath, ok := copyOne(raw); ok {
explicitManifest = append(explicitManifest, targetPath)
}
}
rewriteText := func(text string) string {
text = reSessionUploadPath.ReplaceAllStringFunc(text, func(match string) string {
sub := reSessionUploadPath.FindStringSubmatch(match)
if len(sub) != 3 || sub[1] != sessionID {
return match
}
if targetPath, ok := copyOne(sub[2]); ok {
return targetPath
}
return match
})
text = reContainerFilePath.ReplaceAllStringFunc(text, func(match string) string {
sub := reContainerFilePath.FindStringSubmatch(match)
if len(sub) != 2 {
return match
}
if targetPath, ok := copyOne(sub[1]); ok {
return targetPath
}
return match
})
return text
}
newDesc := rewriteText(description)
newGoal := rewriteText(goal)
if len(explicitManifest) > 0 {
var missing []string
for _, p := range explicitManifest {
if !strings.Contains(newDesc, p) && !strings.Contains(newGoal, p) {
missing = append(missing, p)
}
}
if len(missing) > 0 {
var b strings.Builder
b.WriteString(newDesc)
b.WriteString("\n\n【随任务附带的文件】(位于任务工作目录,可用 Read/Bash 直接打开):")
for _, p := range missing {
fmt.Fprintf(&b, "\n- %s", p)
}
newDesc = b.String()
}
}
return newDesc, newGoal, copied
}
// toolReadTaskFile lets orchestration agents (e.g. auto) safely inspect a
// specific regular file inside a task's workspace without mounting all tasks/
// into the chat sandbox container.
func (s *Server) toolReadTaskFile() actool.CoreTool {
return roTool("read_task_file",
"只读查看指定任务工作目录中的某个文本文件(最多返回 64KB)。用于编排 agent 在容器隔离模式下安全查看子任务产物。",
objSchema(map[string]any{
"task_id": strParam("目标任务 id"),
"path": strParam("任务工作目录内的相对路径或 /workspace/... 路径,如 i12/result.txt 或 uploads/targets.txt"),
}, "task_id", "path"),
func(_ context.Context, in json.RawMessage) (actool.Result, error) {
var a struct {
TaskID string `json:"task_id"`
Path string `json:"path"`
}
_ = json.Unmarshal(in, &a)
t, ok := s.lookupTask(a.TaskID)
if !ok {
return actool.Errorf("任务不存在: " + a.TaskID), nil
}
taskRoot := filepath.Join(s.m.dir, "tasks", t.ID)
resolved, allowed := sandbox.ResolveConfined(taskRoot, "", a.Path)
if !allowed {
return actool.Errorf("非法路径:不允许越出任务工作目录"), nil
}
lfi, err := os.Lstat(resolved)
if err != nil {
return actool.Errorf("文件不存在或无法读取: " + err.Error()), nil
}
if !lfi.Mode().IsRegular() {
return actool.Errorf("仅支持读取普通文件"), nil
}
const maxRead = 64 << 10
f, err := os.Open(resolved)
if err != nil {
return actool.Errorf("打开文件失败: " + err.Error()), nil
}
defer f.Close()
buf := make([]byte, maxRead+1)
n, _ := f.Read(buf)
truncated := n > maxRead
if truncated {
n = maxRead
}
out := string(buf[:n])
if truncated {
out += "\n\n[内容已截断,仅展示前 64KB]"
}
return actool.Text(out), nil
})
}
+112
View File
@@ -0,0 +1,112 @@
package server
import (
"context"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/Autumn-27/artex/internal/sandbox"
)
func TestTransferDraftAndSessionAttachmentsToTask(t *testing.T) {
tmp := t.TempDir()
// Simulate Docker sandbox enabled for path rewriting to /workspace/uploads/...
mgr, err := sandbox.New(sandbox.Config{
Mode: sandbox.ModeDocker,
DockerHost: "unix:///nonexistent.sock",
DataDir: tmp,
HostDataDir: tmp,
})
if err != nil {
t.Fatal(err)
}
prev := sandbox.Default()
sandbox.SetDefault(mgr)
defer sandbox.SetDefault(prev)
// 1. Draft staging upload handoff
draftDir := filepath.Join(tmp, "drafts", "draft-abc", "uploads")
if err := os.MkdirAll(draftDir, 0o755); err != nil {
t.Fatal(err)
}
draftFile := filepath.Join(draftDir, "scope.txt")
if err := os.WriteFile(draftFile, []byte("https://example.com\n"), 0o644); err != nil {
t.Fatal(err)
}
desc := "请测试以下附件中的目标:\n- " + draftFile
newDesc, newGoal, copied := transferDraftUploadsToTask(tmp, "101", desc, "扫描全部目标")
if copied != 1 {
t.Fatalf("draft copied = %d, want 1", copied)
}
if !strings.Contains(newDesc, "/workspace/uploads/scope.txt") {
t.Fatalf("rewritten draft desc = %q", newDesc)
}
if newGoal != "扫描全部目标" {
t.Fatalf("unexpected goal change: %q", newGoal)
}
if b, err := os.ReadFile(filepath.Join(tmp, "tasks", "101", "uploads", "scope.txt")); err != nil || string(b) != "https://example.com\n" {
t.Fatalf("copied draft file check failed: %q, %v", string(b), err)
}
// 2. Auto/chat session -> spawn_task handoff (explicit + inline reference)
sessDir := filepath.Join(tmp, "sessions", "conv-7", "uploads")
if err := os.MkdirAll(sessDir, 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(sessDir, "api.yaml"), []byte("openapi: 3.0.0\n"), 0o644); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(sessDir, "creds.txt"), []byte("user:pass\n"), 0o644); err != nil {
t.Fatal(err)
}
desc2, goal2, copied2 := transferSessionAttachmentsToTask(
tmp, "conv-7", "202",
[]string{"uploads/creds.txt"},
"分析接口文档 /workspace/uploads/api.yaml",
"测试所有鉴权接口",
)
if copied2 != 2 {
t.Fatalf("session copied = %d, want 2", copied2)
}
if !strings.Contains(desc2, "/workspace/uploads/api.yaml") || !strings.Contains(desc2, "/workspace/uploads/creds.txt") {
t.Fatalf("rewritten session desc = %q", desc2)
}
if goal2 != "测试所有鉴权接口" {
t.Fatalf("unexpected goal2: %q", goal2)
}
for _, fn := range []string{"api.yaml", "creds.txt"} {
if _, err := os.Stat(filepath.Join(tmp, "tasks", "202", "uploads", fn)); err != nil {
t.Fatalf("expected %s in task 202 uploads: %v", fn, err)
}
}
}
func TestAcquireSandboxBrowserSlotCapsConcurrencyAndHonorsCancel(t *testing.T) {
key := "task:browser-slot-test"
rel1, err := acquireSandboxBrowserSlot(t.Context(), key)
if err != nil {
t.Fatalf("slot 1: %v", err)
}
defer rel1()
rel2, err := acquireSandboxBrowserSlot(t.Context(), key)
if err != nil {
t.Fatalf("slot 2: %v", err)
}
// Third concurrent browser for the same task must block until timeout/release.
cctx, cancel := context.WithTimeout(t.Context(), 40*time.Millisecond)
defer cancel()
if _, err := acquireSandboxBrowserSlot(cctx, key); err == nil {
t.Fatalf("expected 3rd slot to block and fail on context deadline")
}
// Releasing slot 2 immediately allows a new acquisition (idempotent double-release safe).
rel2()
rel2()
rel3, err := acquireSandboxBrowserSlot(t.Context(), key)
if err != nil {
t.Fatalf("slot after release: %v", err)
}
rel3()
}
+44 -9
View File
@@ -24,6 +24,7 @@ import (
"github.com/Autumn-27/artex/db"
"github.com/Autumn-27/artex/intercept"
"github.com/Autumn-27/artex/intercept/jev"
"github.com/Autumn-27/artex/internal/sandbox"
"github.com/Autumn-27/artex/llmpool"
"github.com/Autumn-27/artex/llmrec"
"github.com/Autumn-27/artex/report"
@@ -169,6 +170,7 @@ type triggeredRun struct {
taskDesc string // 任务描述(任务级,同任务相同);合并时只渲染一次
taskGoal string // 任务目标(任务级,同任务相同);合并时只渲染一次
mergeable bool // true for finding/goal event triggers (merge by taskID)
multiTask bool // true when mergeAllRuns combined events from multiple distinct tasks
}
func New(ctx context.Context, m *Manager, skillDir string, dataDir string, keyDir string) *Server {
@@ -282,9 +284,6 @@ func New(ctx context.Context, m *Manager, skillDir string, dataDir string, keyDi
// 漏洞 IM 推送投递引擎。与 Scheduler 并列但独立:推送的实时性要求(3s)
// 与触发器的业务节奏不同,且两者失败互不牵连——推送卡住不该影响 agent 触发。
go newNotifier(s).Run(s.ctx)
// Fill the tool cache for any enabled MCP that has none yet (notably the
// seeded browser MCP on first run). Async so it never blocks startup.
go s.discoverEmptyMCPsOnStartup()
logSink.SetDB(ctx, m.pg) // restore last 100 log rows and enable async persistence
}
// precedence: persisted DB config > env.
@@ -304,6 +303,12 @@ func New(ctx context.Context, m *Manager, skillDir string, dataDir string, keyDi
log.Printf("[engine] no LLM provider configured — engine idle until set via /api/llm or env")
}
s.restoreTaskRuntimes()
s.initSandbox()
if m.pg != nil {
// Fill the tool cache for any enabled MCP (notably browser MCP) AFTER
// initSandbox so stdio discovery runs inside the sandbox container.
go s.discoverEmptyMCPsOnStartup()
}
s.ensureProxySupervisor()
s.proxyPoolWG.Add(1)
go func() { defer s.proxyPoolWG.Done(); s.runProxyPoolSupervisor(s.ctx) }()
@@ -323,13 +328,17 @@ func New(ctx context.Context, m *Manager, skillDir string, dataDir string, keyDi
return s
}
// Close waits for proxy pool supervision to stop before Manager closes the DB.
// Close waits for proxy pool supervision to stop and stops running sandboxes before DB close.
func (s *Server) Close() {
if s != nil {
s.proxyPoolWG.Wait()
if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() {
sctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
mgr.Shutdown(sctx)
cancel()
}
}
}
// Restored deadline and worker loops must inherit the same context as new tasks,
// including the side-question checkpoint publisher installed during startup.
func (s *Server) restoreTaskRuntimes() {
@@ -1167,6 +1176,20 @@ func (s *Server) Handler() http.Handler {
mux.HandleFunc("PUT /api/intercept/judge", s.interceptSetJudgeConfig)
mux.HandleFunc("GET /api/intercept/judge/usage", s.interceptJudgeUsage) // 兜底审批累计 token 用量
// 沙箱容器隔离状态、配置与启停管理
mux.HandleFunc("GET /api/sandbox/status", s.sandboxStatus)
mux.HandleFunc("PUT /api/sandbox/settings", s.updateSandboxSettings)
mux.HandleFunc("POST /api/sandbox/prune", s.pruneSandboxContainers)
mux.HandleFunc("GET /api/sandbox/containers/{scope}/{id}", s.getSandboxContainer)
mux.HandleFunc("POST /api/sandbox/containers/{scope}/{id}/start", s.startSandboxContainer)
mux.HandleFunc("POST /api/sandbox/containers/{scope}/{id}/stop", s.stopSandboxContainer)
mux.HandleFunc("POST /api/sandbox/containers/{scope}/{id}/recreate", s.recreateSandboxContainer)
mux.HandleFunc("DELETE /api/sandbox/containers/{scope}/{id}", s.removeSandboxContainer)
mux.HandleFunc("GET /api/tasks/{id}/sandbox", s.getTaskSandbox)
mux.HandleFunc("POST /api/tasks/{id}/sandbox/start", s.startTaskSandbox)
mux.HandleFunc("POST /api/tasks/{id}/sandbox/stop", s.stopTaskSandbox)
mux.HandleFunc("POST /api/tasks/{id}/sandbox/recreate", s.recreateTaskSandbox)
// /api/* goes through CORS + JWT; everything else is served by the embedded
// frontend (no JWT required; the optional Basic Auth gate wraps both). With the
// no-embed build the webui handler just 404s (run `next dev` separately).
@@ -1180,9 +1203,8 @@ func (s *Server) Handler() http.Handler {
top := http.NewServeMux()
top.HandleFunc(mcpEndpointPath, s.serveMCP)
top.Handle("/", s.requireBasicAuth(root))
return top
return s.blockSandboxAdminAccess(top)
}
// --- handlers ---
// health requires the optional Basic Auth gate but no admin JWT, and exposes no application fingerprints.
@@ -1882,6 +1904,13 @@ func (s *Server) createTaskFromRequest(req createTaskReq) (*Task, *taskCreateErr
}
return nil, &taskCreateError{500, err.Error()}
}
if newDesc, newGoal, copied := transferDraftUploadsToTask(s.m.dir, t.ID, req.Description, req.Goal); copied > 0 {
req.Description, req.Goal = newDesc, newGoal
t.Description, t.Goal = newDesc, newGoal
if id, e := strconv.ParseInt(t.ID, 10, 64); e == nil && s.m.pg != nil {
_, _ = s.m.pg.Exec(`UPDATE tasks SET description=$2, goal=$3 WHERE id=$1`, id, newDesc, newGoal)
}
}
log.Printf("[task] 新建任务 #%s «%s» 目标: %s", t.ID, req.Description, req.Goal)
// 共享的建后流程(seed + 种子意图 + 后台目标分解 + engine.Run),与 spawn_task 复用同一段。
// launchTask 内部异步,不阻塞 UI —— 目标分解在后台可见地进行。
@@ -4616,12 +4645,18 @@ func (s *Server) chat(w http.ResponseWriter, r *http.Request) {
// 把上传附件的【绝对路径】清单拼进发给 agent 的消息,它据此用 Read/Bash 打开文件。
// taskDir = agent 的工作目录(CWD),与 chatUpload 落盘、ensureRunDir 一致。
taskDir := filepath.Join(s.m.dir, "tasks", t.ID)
agentMsg := composeAgentMessage(agentMessage, req.Attachments, taskDir)
attachDir := taskDir
if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() {
attachDir = sandbox.ContainerWorkDir
}
agentMsg := composeAgentMessage(agentMessage, req.Attachments, attachDir)
s.engine.BeginLLMCall(t.ID)
_, err := ma.Chat(ctx, maTaskID, mainSeg, s.m.Assets(), t.Store, t.Goal, agentMsg, emit, t.Notify, resume, t.NotifyGoal, t.NotifyHint)
s.engine.EndLLMCall(t.ID)
if mgr := sandbox.Default(); mgr != nil && mgr.Enabled() && s.resolvedTaskStatus(t) != "running" {
mgr.RequestIdleStop(sandbox.Target{Scope: sandbox.ScopeTask, OwnerID: t.ID})
}
if err != nil && ctx.Err() == nil {
s.engine.emitActivity(t, db.Activity{Worker: "mainagent", Kind: "text", IsError: true, Summary: "(主 Agent 出错:" + err.Error() + ")", MainSeg: segPtr})
}
}()
writeJSON(w, 202, map[string]any{"status": "accepted", "mode": "llm"})
+13 -5
View File
@@ -10,8 +10,9 @@ import (
"sort"
"strings"
"time"
)
"github.com/Autumn-27/artex/internal/sandbox"
)
// Workspace file manager — browse / view / edit / download / upload / delete the
// shared work dir (s.m.dir), where all agents write their artifacts. Every path is
// confined to the work dir root (traversal via ".." is neutralised). All routes sit
@@ -33,7 +34,12 @@ func (s *Server) wsResolve(rel string) (string, bool) {
if abs != base && !strings.HasPrefix(abs, base+string(os.PathSeparator)) {
return "", false
}
return abs, true
// Block symlink escapes planted by a compromised sandbox container.
resolved, ok := sandbox.CheckPathWithinRoot(base, abs)
if !ok {
return "", false
}
return resolved, true
}
// wsRel renders an absolute path back as a workspace-relative path (forward slashes).
@@ -226,9 +232,11 @@ func (s *Server) wsPreview(w http.ResponseWriter, r *http.Request) {
if filepath.IsAbs(rawPath) {
base := filepath.Clean(s.m.dir)
candidate := filepath.Clean(rawPath)
ok = candidate == base || strings.HasPrefix(candidate, base+string(os.PathSeparator))
if ok {
abs = candidate
if resolved, within := sandbox.CheckPathWithinRoot(base, candidate); within {
abs = resolved
ok = true
} else {
ok = false
}
}
if !ok {
+255
View File
@@ -0,0 +1,255 @@
package traffic
import (
"fmt"
"net"
"os"
"strconv"
"strings"
"sync"
)
// SSRFGuardConfig controls which destinations the recording proxy refuses to dial.
// Loopback, link-local / cloud metadata, and ARTEX's own internal services are
// always blocked when the guard is enabled. Private RFC1918 networks are allowed
// by default so authorized internal pentests keep working, and can be blocked by
// setting BlockPrivate=true.
type SSRFGuardConfig struct {
Enabled bool
BlockPrivate bool
BlockedHosts []string
BlockedCIDRs []*net.IPNet
// InfraIPs are machines that also host ordinary scan targets (for example the
// ARTEX host LAN address, where :18080 may be in scope). Every port on those
// addresses stays reachable except AdminPorts, which would reach this process.
InfraIPs []net.IP
AdminPorts []int
}
type ssrfGuard struct {
mu sync.RWMutex
enabled bool
blockPrivate bool
blockedHosts map[string]struct{}
blockedIPs map[string]struct{}
blockedCIDRs []*net.IPNet
infraIPs []net.IP
adminPorts map[string]struct{}
}
var (
alwaysBlockedCIDRs = mustParseCIDRs(
"0.0.0.0/8",
"127.0.0.0/8",
"169.254.0.0/16",
"::1/128",
"::/128",
"fe80::/10",
"ff00::/8",
)
privateCIDRs = mustParseCIDRs(
"10.0.0.0/8",
"172.16.0.0/12",
"192.168.0.0/16",
"fc00::/7",
)
alwaysBlockedHostnames = map[string]struct{}{
"localhost": {},
"metadata.google.internal": {},
"metadata.goog": {},
"host.docker.internal": {},
"gateway.docker.internal": {},
}
)
func mustParseCIDRs(raw ...string) []*net.IPNet {
out := make([]*net.IPNet, 0, len(raw))
for _, s := range raw {
_, ipnet, err := net.ParseCIDR(s)
if err == nil {
out = append(out, ipnet)
}
}
return out
}
func newSSRFGuard(cfg SSRFGuardConfig) *ssrfGuard {
g := &ssrfGuard{
enabled: cfg.Enabled,
blockPrivate: cfg.BlockPrivate,
blockedHosts: make(map[string]struct{}),
blockedIPs: make(map[string]struct{}),
blockedCIDRs: append([]*net.IPNet(nil), cfg.BlockedCIDRs...),
adminPorts: map[string]struct{}{"8787": {}, "8788": {}},
}
for _, p := range cfg.AdminPorts {
if p > 0 && p < 65536 {
g.adminPorts[strconv.Itoa(p)] = struct{}{}
}
}
for _, ip := range cfg.InfraIPs {
if ip = normalizeIP(ip); ip != nil {
g.infraIPs = append(g.infraIPs, ip)
}
}
for _, h := range cfg.BlockedHosts {
h = strings.ToLower(strings.TrimSpace(h))
if h == "" {
continue
}
if ip := net.ParseIP(h); ip != nil {
g.blockedIPs[ip.String()] = struct{}{}
continue
}
g.blockedHosts[h] = struct{}{}
if ips, err := net.LookupIP(h); err == nil {
for _, ip := range ips {
g.blockedIPs[ip.String()] = struct{}{}
}
}
}
// Always block local interface IPs so a sandboxed container cannot use the
// recording proxy to reach ARTEX's own management port (:8787) via its container IP.
if addrs, err := net.InterfaceAddrs(); err == nil {
for _, a := range addrs {
if ipnet, ok := a.(*net.IPNet); ok && ipnet.IP != nil {
g.blockedIPs[normalizeIP(ipnet.IP).String()] = struct{}{}
}
}
}
// The container default gateway is the Docker host bridge. Blocking it stops
// the proxy from hairpinning back onto published host ports.
if gw := linuxDefaultGatewayIPv4(); gw != nil {
g.blockedIPs[gw.String()] = struct{}{}
}
return g
}
func normalizeIP(ip net.IP) net.IP {
if ip == nil {
return nil
}
if v4 := ip.To4(); v4 != nil {
return v4
}
return ip
}
// linuxDefaultGatewayIPv4 reads the IPv4 default route. Missing on non-Linux
// and in unit tests that do not mount /proc; callers treat nil as "unknown".
func linuxDefaultGatewayIPv4() net.IP {
data, err := os.ReadFile("/proc/net/route")
if err != nil {
return nil
}
lines := strings.Split(string(data), "\n")
for _, line := range lines[1:] {
fields := strings.Fields(line)
if len(fields) < 3 || fields[1] != "00000000" {
continue
}
gw, err := strconv.ParseUint(fields[2], 16, 32)
if err != nil || gw == 0 {
continue
}
return net.IPv4(byte(gw), byte(gw>>8), byte(gw>>16), byte(gw>>24)).To4()
}
return nil
}
// Check returns a non-empty denial reason if rawHost (host or host:port) is blocked.
func (g *ssrfGuard) Check(rawHost string) string {
if g == nil {
return ""
}
g.mu.RLock()
defer g.mu.RUnlock()
if !g.enabled {
return ""
}
host, port := splitHostAndPort(rawHost)
host = strings.ToLower(strings.TrimSpace(host))
host = strings.TrimPrefix(host, "[")
host = strings.TrimSuffix(host, "]")
if host == "" {
return "empty target host"
}
if _, ok := alwaysBlockedHostnames[host]; ok || strings.HasSuffix(host, ".localhost") {
return fmt.Sprintf("internal host %q is blocked", host)
}
if _, ok := g.blockedHosts[host]; ok {
return fmt.Sprintf("protected service host %q is blocked", host)
}
if ip := net.ParseIP(host); ip != nil {
if reason := g.checkIP(ip); reason != "" {
return reason
}
return g.checkInfraPort(ip, port)
}
// Resolve hostname to guard against DNS rebinding / internal Docker DNS names.
ips, err := net.LookupIP(host)
if err != nil {
return ""
}
for _, ip := range ips {
if reason := g.checkIP(ip); reason != "" {
return fmt.Sprintf("%s (resolved from %s)", reason, host)
}
if reason := g.checkInfraPort(ip, port); reason != "" {
return reason
}
}
return ""
}
func splitHostAndPort(raw string) (string, string) {
raw = strings.TrimSpace(raw)
if h, p, err := net.SplitHostPort(raw); err == nil {
return h, p
}
return raw, ""
}
func (g *ssrfGuard) checkInfraPort(ip net.IP, port string) string {
if port == "" || len(g.infraIPs) == 0 {
return ""
}
if _, ok := g.adminPorts[port]; !ok {
return ""
}
ip = normalizeIP(ip)
for _, infra := range g.infraIPs {
if infra.Equal(ip) {
return fmt.Sprintf("ARTEX admin port %s on %s is blocked", port, ip.String())
}
}
return ""
}
func (g *ssrfGuard) checkIP(ip net.IP) string {
if ip == nil {
return ""
}
ip = normalizeIP(ip)
if _, ok := g.blockedIPs[ip.String()]; ok {
return fmt.Sprintf("protected host IP %s is blocked", ip.String())
}
for _, n := range alwaysBlockedCIDRs {
if n.Contains(ip) {
return fmt.Sprintf("restricted address %s (%s) is blocked", ip.String(), n.String())
}
}
for _, n := range g.blockedCIDRs {
if n.Contains(ip) {
return fmt.Sprintf("sandbox/internal network address %s (%s) is blocked", ip.String(), n.String())
}
}
if g.blockPrivate {
for _, n := range privateCIDRs {
if n.Contains(ip) {
return fmt.Sprintf("private network address %s (%s) is blocked", ip.String(), n.String())
}
}
}
return ""
}
+69
View File
@@ -0,0 +1,69 @@
package traffic
import (
"net"
"testing"
)
func TestSSRFGuardBlocksLoopbackMetadataProtectedAndOptionalPrivate(t *testing.T) {
_, sbxNet, _ := net.ParseCIDR("172.29.0.0/16")
g := newSSRFGuard(SSRFGuardConfig{
Enabled: true,
BlockPrivate: false,
BlockedHosts: []string{"postgres", "docker-socket-proxy", "10.99.0.2"},
BlockedCIDRs: []*net.IPNet{sbxNet},
})
blocked := []string{
"127.0.0.1:8787",
"127.0.0.2:80",
"[::1]:8787",
"localhost:8787",
"foo.localhost:80",
"169.254.169.254:80",
"metadata.google.internal:80",
"postgres:5432",
"docker-socket-proxy:2375",
"10.99.0.2:5432",
"172.29.0.15:8080",
}
for _, h := range blocked {
if reason := g.Check(h); reason == "" {
t.Fatalf("expected %q to be blocked", h)
}
}
// Authorized internal target allowed when BlockPrivate=false
if reason := g.Check("192.168.110.50:8080"); reason != "" {
t.Fatalf("expected internal target allowed when BlockPrivate=false, got: %s", reason)
}
if reason := g.Check("93.184.216.34:443"); reason != "" {
t.Fatalf("expected public IP allowed, got: %s", reason)
}
// Private targets blocked when BlockPrivate=true
strict := newSSRFGuard(SSRFGuardConfig{Enabled: true, BlockPrivate: true})
if reason := strict.Check("192.168.110.50:8080"); reason == "" {
t.Fatalf("expected private IP blocked when BlockPrivate=true")
}
if reason := strict.Check("10.0.0.1:80"); reason == "" {
t.Fatalf("expected 10/8 blocked when BlockPrivate=true")
}
infra := newSSRFGuard(SSRFGuardConfig{
Enabled: true,
InfraIPs: []net.IP{net.ParseIP("192.168.110.238")},
})
if reason := infra.Check("192.168.110.238:8787"); reason == "" {
t.Fatal("expected admin port on the ARTEX host to be blocked")
}
if reason := infra.Check("192.168.110.238:8788"); reason == "" {
t.Fatal("expected recording proxy port on the ARTEX host to be blocked")
}
if reason := infra.Check("192.168.110.238:18080"); reason != "" {
t.Fatalf("expected ordinary target port on the ARTEX host to stay open, got %s", reason)
}
if reason := infra.Check("192.168.110.50:8787"); reason != "" {
t.Fatalf("expected another LAN host on 8787 to stay open, got %s", reason)
}
}
+151
View File
@@ -0,0 +1,151 @@
package traffic
import (
"bufio"
"io"
"net"
"net/http"
"net/url"
"strings"
"sync/atomic"
"testing"
"time"
)
func freeLoopbackAddr(t *testing.T) string {
t.Helper()
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
addr := ln.Addr().String()
ln.Close()
return addr
}
func startProxy(t *testing.T, guard bool) (*Traffic, string) {
t.Helper()
addr := freeLoopbackAddr(t)
tr, err := Open(t.TempDir(), addr)
if err != nil {
t.Fatal(err)
}
if guard {
tr.EnableSSRFGuard(SSRFGuardConfig{Enabled: true})
}
go func() { _ = tr.Start() }()
t.Cleanup(func() {
_ = tr.proxy.Close()
_ = tr.Close()
})
deadline := time.Now().Add(3 * time.Second)
for time.Now().Before(deadline) {
conn, err := net.DialTimeout("tcp", addr, 100*time.Millisecond)
if err == nil {
conn.Close()
return tr, addr
}
time.Sleep(20 * time.Millisecond)
}
t.Fatal("proxy did not start listening")
return nil, ""
}
func TestProxySSRFGuardBlocksLoopbackHTTPAndConnect(t *testing.T) {
var hits atomic.Int32
upstream, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer upstream.Close()
go func() {
for {
conn, err := upstream.Accept()
if err != nil {
return
}
hits.Add(1)
_, _ = io.WriteString(conn, "HTTP/1.1 200 OK\r\nContent-Length: 11\r\nConnection: close\r\n\r\n{\"ok\":true}")
conn.Close()
}
}()
_, proxyAddr := startProxy(t, true)
proxyURL, _ := url.Parse("http://" + proxyAddr)
client := &http.Client{
Timeout: 3 * time.Second,
Transport: &http.Transport{Proxy: http.ProxyURL(proxyURL)},
}
resp, err := client.Get("http://" + upstream.Addr().String() + "/api/health")
if err != nil {
t.Fatalf("guarded http request: %v", err)
}
body, _ := io.ReadAll(resp.Body)
resp.Body.Close()
if resp.StatusCode != http.StatusForbidden {
t.Fatalf("status=%d body=%s", resp.StatusCode, body)
}
if !strings.Contains(string(body), "blocked by ARTEX proxy SSRF guard") {
t.Fatalf("body=%s", body)
}
if hits.Load() != 0 {
t.Fatalf("proxy dialed loopback %d times", hits.Load())
}
conn, err := net.Dial("tcp", proxyAddr)
if err != nil {
t.Fatal(err)
}
defer conn.Close()
target := upstream.Addr().String()
if _, err := io.WriteString(conn, "CONNECT "+target+" HTTP/1.1\r\nHost: "+target+"\r\n\r\n"); err != nil {
t.Fatal(err)
}
_ = conn.SetReadDeadline(time.Now().Add(3 * time.Second))
status, err := bufio.NewReader(conn).ReadString('\n')
if err != nil {
t.Fatal(err)
}
if !strings.Contains(status, "502") && !strings.Contains(status, "403") {
t.Fatalf("CONNECT status=%q", status)
}
time.Sleep(150 * time.Millisecond)
if hits.Load() != 0 {
t.Fatalf("CONNECT dialed loopback %d times", hits.Load())
}
}
func TestProxyForwardsLoopbackWhenGuardDisabled(t *testing.T) {
upstream := http.Server{}
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
hits := 0
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
hits++
w.Write([]byte("ok"))
})
upstream.Handler = mux
go upstream.Serve(ln)
defer upstream.Close()
_, proxyAddr := startProxy(t, false)
proxyURL, _ := url.Parse("http://" + proxyAddr)
client := &http.Client{
Timeout: 3 * time.Second,
Transport: &http.Transport{Proxy: http.ProxyURL(proxyURL)},
}
resp, err := client.Get("http://" + ln.Addr().String() + "/")
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if resp.StatusCode != 200 {
t.Fatalf("status=%d", resp.StatusCode)
}
if hits != 1 {
t.Fatalf("hits=%d", hits)
}
}
+87 -2
View File
@@ -172,6 +172,21 @@ type Traffic struct {
upstream atomic.Pointer[url.URL]
upstreamMu sync.RWMutex
upstreamFailure func(error)
ssrf atomic.Pointer[ssrfGuard]
}
// EnableSSRFGuard installs an outbound destination filter on the recording
// proxy so sandboxed workloads cannot pivot to localhost, cloud metadata, or
// ARTEX's own management/database endpoints.
func (t *Traffic) EnableSSRFGuard(cfg SSRFGuardConfig) {
if t == nil {
return
}
if !cfg.Enabled {
t.ssrf.Store(nil)
return
}
t.ssrf.Store(newSSRFGuard(cfg))
}
// Open initializes the traffic tree, blob store and SQLite index under dir.
@@ -220,12 +235,28 @@ func Open(dir, addr string) (*Traffic, error) {
// a direct dial. When a global egress proxy IS configured (SetUpstreamProxy),
// every captured request — intercepted AND transparently tunneled — is
// forwarded through it instead, so no host leaks the real source IP.
p.SetUpstreamProxy(func(*http.Request) (*url.URL, error) { return t.upstream.Load(), nil })
// Dial-time rejection. Requestheaders can answer a plain HTTP proxy request
// with 403, but a CONNECT (HTTPS) still dials the target unless this returns
// an error: go-mitmproxy ignores a synthetic response on the CONNECT path.
p.SetUpstreamProxy(func(req *http.Request) (*url.URL, error) {
if err := t.rejectBlockedDestination(req); err != nil {
return nil, err
}
return t.upstream.Load(), nil
})
// Fail-open: MITM every host by default, EXCEPT ones a prior request proved we
// can't intercept without breaking (see maybePassthrough). Those are tunneled
// transparently so the request still reaches the target instead of being killed.
// Blocked destinations stay intercepted so the addon can return 403 before dial.
p.SetShouldInterceptRule(func(req *http.Request) bool {
_, tunnel := t.pass.Load(hostOnly(req.Host))
if g := t.ssrf.Load(); g != nil && req != nil && g.Check(req.Host) != "" {
return true
}
host := ""
if req != nil {
host = req.Host
}
_, tunnel := t.pass.Load(hostOnly(host))
return !tunnel
})
p.AddAddon(&sink{t: t})
@@ -233,6 +264,31 @@ func Open(dir, addr string) (*Traffic, error) {
return t, nil
}
// rejectBlockedDestination refuses to dial loopback, metadata, and the hosts
// configured on the SSRF guard. An empty host is left to the caller: some
// internal proxy requests have no target yet, and blocking those would drop
// legitimate traffic.
func (t *Traffic) rejectBlockedDestination(req *http.Request) error {
if t == nil || req == nil {
return nil
}
g := t.ssrf.Load()
if g == nil {
return nil
}
host := req.Host
if host == "" && req.URL != nil {
host = req.URL.Host
}
if strings.TrimSpace(host) == "" {
return nil
}
if reason := g.Check(host); reason != "" {
return fmt.Errorf("blocked by ARTEX proxy SSRF guard: %s", reason)
}
return nil
}
// initIndex applies the schema on a single pinned connection. Pinning is what
// makes auto_vacuum reliable: it can only be set while the database still holds
// no tables, and only the VACUUM that follows writes it into the file header —
@@ -426,6 +482,25 @@ func (s *sink) Requestheaders(f *mproxy.Flow) {
if f.Request == nil {
return
}
if s.t != nil {
if g := s.t.ssrf.Load(); g != nil {
host := ""
if f.Request.URL != nil {
host = f.Request.URL.Host
}
if host == "" && f.Request.Header != nil {
host = f.Request.Header.Get("Host")
}
if reason := g.Check(host); reason != "" {
f.Response = &mproxy.Response{
StatusCode: http.StatusForbidden,
Header: http.Header{"Content-Type": []string{"text/plain; charset=utf-8"}},
Body: []byte("blocked by ARTEX proxy SSRF guard: " + reason),
}
return
}
}
}
if f.Request.Header == nil {
f.Request.Header = make(http.Header)
}
@@ -434,6 +509,16 @@ func (s *sink) Requestheaders(f *mproxy.Flow) {
}
}
func (s *sink) ServerConnected(connCtx *mproxy.ConnContext) {
if connCtx == nil || connCtx.ServerConn == nil || s.t == nil {
return
}
if g := s.t.ssrf.Load(); g != nil {
if reason := g.Check(connCtx.ServerConn.Address); reason != "" && connCtx.ServerConn.Conn != nil {
_ = connCtx.ServerConn.Conn.Close()
}
}
}
func (s *sink) Response(f *mproxy.Flow) {
if f.Request == nil || f.Response == nil {
return
@@ -0,0 +1,411 @@
"use client";
import * as React from "react";
import Link from "next/link";
import {
BoxIcon,
ExternalLinkIcon,
PlayIcon,
RefreshCwIcon,
RotateCcwIcon,
SquareIcon,
Trash2Icon,
} from "lucide-react";
import { toast } from "sonner";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Label } from "@/components/ui/label";
import {
Popover,
PopoverContent,
PopoverDescription,
PopoverHeader,
PopoverTitle,
PopoverTrigger,
} from "@/components/ui/popover";
import { useLiveTranslation } from "@/i18n/use-live-translation";
import { api } from "@/lib/api";
import type { SandboxContainerInfo } from "@/lib/types";
function fmtBytes(n?: number): string {
if (!n || n <= 0) return "0 B";
if (n >= 1 << 30) return `${(n / (1 << 30)).toFixed(2)} GiB`;
if (n >= 1 << 20) return `${(n / (1 << 20)).toFixed(1)} MiB`;
if (n >= 1 << 10) return `${(n / (1 << 10)).toFixed(1)} KiB`;
return `${n} B`;
}
function fmtUptime(startedAt?: string): string {
if (!startedAt) return "-";
const ts = Date.parse(startedAt);
if (Number.isNaN(ts)) return "-";
const sec = Math.max(0, Math.floor((Date.now() - ts) / 1000));
if (sec < 60) return `${sec}s`;
const min = Math.floor(sec / 60);
if (min < 60) return `${min}m ${sec % 60}s`;
const hr = Math.floor(min / 60);
if (hr < 24) return `${hr}h ${min % 60}m`;
return `${Math.floor(hr / 24)}d ${hr % 24}h`;
}
export function SessionSandboxControl({
conversationId,
running: chatRunning,
}: {
conversationId: number;
running: boolean;
}) {
const { i18n } = useLiveTranslation();
const isEn = i18n.language.startsWith("en");
const L = (zh: string, en: string) => (isEn ? en : zh);
const ownerID = `conv-${conversationId}`;
const [open, setOpen] = React.useState(false);
const [info, setInfo] = React.useState<SandboxContainerInfo | null>(null);
const [loading, setLoading] = React.useState(false);
const [busy, setBusy] = React.useState<"" | "start" | "stop" | "recreate" | "remove">("");
const [recreateOpen, setRecreateOpen] = React.useState(false);
const [clearWorkspace, setClearWorkspace] = React.useState(false);
const [removeOpen, setRemoveOpen] = React.useState(false);
const fetchInfo = React.useCallback(
async (withStats: boolean) => {
setLoading(true);
try {
const res = await api.sandboxContainer("session", ownerID, withStats);
setInfo(res);
} catch {
// Ignore transient poll errors; popover refresh button lets user retry.
} finally {
setLoading(false);
}
},
[ownerID],
);
React.useEffect(() => {
setInfo(null);
void fetchInfo(false);
}, [fetchInfo]);
React.useEffect(() => {
if (!open) return;
void fetchInfo(true);
}, [open, fetchInfo]);
// Refresh container status when a chat turn completes (a tool call may have started it).
const prevRunningRef = React.useRef(chatRunning);
React.useEffect(() => {
if (prevRunningRef.current && !chatRunning) {
void fetchInfo(open);
}
prevRunningRef.current = chatRunning;
}, [chatRunning, open, fetchInfo]);
// Hide completely when running in local (non-Docker) mode.
if (!info || info.state === "local") {
return null;
}
const running = info.state === "running";
const exists = info.state !== "missing";
let stateLabel = info.state;
if (info.state === "running") stateLabel = L("沙箱运行中", "Sandbox Running");
else if (info.state === "exited") stateLabel = L("沙箱已停止", "Sandbox Stopped");
else if (info.state === "missing") stateLabel = L("沙箱未创建", "Sandbox Standby");
else if (info.state === "error") stateLabel = L("沙箱异常", "Sandbox Error");
let dotClass = "bg-muted-foreground/50";
if (running) dotClass = "bg-emerald-500";
else if (info.state === "error") dotClass = "bg-red-500";
const handleStart = async () => {
setBusy("start");
try {
const res = await api.startSandboxContainer("session", ownerID);
setInfo(res);
toast.success(L("会话沙箱容器已启动", "Session sandbox container started"));
} catch (e) {
toast.error(e instanceof Error ? e.message : String(e));
} finally {
setBusy("");
}
};
const handleStop = async () => {
setBusy("stop");
try {
const res = await api.stopSandboxContainer("session", ownerID);
setInfo(res);
toast.success(L("会话沙箱容器已停止(内存已释放)", "Session sandbox container stopped"));
} catch (e) {
toast.error(e instanceof Error ? e.message : String(e));
} finally {
setBusy("");
}
};
const executeRecreate = async () => {
const wipe = clearWorkspace;
setRecreateOpen(false);
setClearWorkspace(false);
setBusy("recreate");
try {
const res = await api.recreateSandboxContainer("session", ownerID, { clear_workspace: wipe });
setInfo(res);
toast.success(
wipe
? L("会话沙箱已重建并清空工作区", "Session sandbox recreated with clean workspace")
: L("会话沙箱已重建(工作区文件已保留)", "Session sandbox recreated"),
);
} catch (e) {
toast.error(e instanceof Error ? e.message : String(e));
} finally {
setBusy("");
}
};
const executeRemove = async () => {
setRemoveOpen(false);
setBusy("remove");
try {
await api.removeSandboxContainer("session", ownerID);
await fetchInfo(false);
toast.success(L("会话沙箱容器已删除(工作区文件已保留)", "Session sandbox container removed"));
} catch (e) {
toast.error(e instanceof Error ? e.message : String(e));
} finally {
setBusy("");
}
};
return (
<>
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button size="sm" variant="outline" className="h-7 gap-1.5 px-2 text-xs">
<BoxIcon className="size-3.5" />
<span className={`size-1.5 rounded-full ${dotClass}`} />
<span className="hidden sm:inline">{stateLabel}</span>
</Button>
</PopoverTrigger>
<PopoverContent align="end" className="w-80 space-y-3 text-xs">
<PopoverHeader>
<PopoverTitle className="flex items-center justify-between text-sm">
<span className="flex items-center gap-1.5">
<BoxIcon className="size-4" />
{L("对话隔离沙箱", "Chat Sandbox")}
</span>
<Badge variant={running ? "default" : "secondary"}>{info.state}</Badge>
</PopoverTitle>
<PopoverDescription className="text-xs">
{L(
"本对话调用命令、脚本或浏览器时将在此独立非 root 容器内执行(按需自动创建,空闲自动停机)。",
"Commands, scripts, and browser tools in this chat run inside this isolated non-root container (created on demand).",
)}
</PopoverDescription>
</PopoverHeader>
<div className="space-y-1.5 rounded-md border bg-muted/40 p-2.5 font-mono text-[11px]">
<div className="flex justify-between gap-2">
<span className="text-muted-foreground">{L("会话", "Session")}</span>
<span className="truncate">{ownerID}</span>
</div>
<div className="flex justify-between gap-2">
<span className="text-muted-foreground">{L("容器", "Container")}</span>
<span className="truncate">{info.short_id || "-"}</span>
</div>
<div className="flex justify-between gap-2">
<span className="text-muted-foreground">{L("镜像", "Image")}</span>
<span className="truncate" title={info.image}>
{info.image}
</span>
</div>
<div className="flex justify-between gap-2">
<span className="text-muted-foreground">{L("网络", "Network")}</span>
<span className="truncate">{info.network || "-"}</span>
</div>
<div className="flex justify-between gap-2">
<span className="text-muted-foreground">{L("活跃执行", "Active runs")}</span>
<span>{info.active_runs}</span>
</div>
{running ? (
<>
<div className="flex justify-between gap-2">
<span className="text-muted-foreground">{L("运行时长", "Uptime")}</span>
<span>{fmtUptime(info.started_at)}</span>
</div>
<div className="flex justify-between gap-2">
<span className="text-muted-foreground">CPU</span>
<span>{(info.cpu_percent ?? 0).toFixed(1)}%</span>
</div>
<div className="flex justify-between gap-2">
<span className="text-muted-foreground">{L("内存", "Memory")}</span>
<span>
{fmtBytes(info.mem_usage_bytes)}
{info.mem_limit_bytes ? ` / ${fmtBytes(info.mem_limit_bytes)}` : ""}
</span>
</div>
{info.pids_current != null ? (
<div className="flex justify-between gap-2">
<span className="text-muted-foreground">PIDs</span>
<span>{info.pids_current}</span>
</div>
) : null}
</>
) : null}
{info.error ? <p className="break-all text-destructive">{info.error}</p> : null}
</div>
<div className="flex flex-wrap items-center gap-1.5">
{!running ? (
<Button
size="sm"
variant="default"
className="h-7 flex-1 gap-1 text-xs"
disabled={busy !== ""}
onClick={() => void handleStart()}
>
<PlayIcon className="size-3.5" />
{busy === "start" ? L("启动中…", "Starting…") : L("启动", "Start")}
</Button>
) : (
<Button
size="sm"
variant="outline"
className="h-7 flex-1 gap-1 text-xs"
disabled={busy !== ""}
onClick={() => void handleStop()}
>
<SquareIcon className="size-3.5" />
{busy === "stop" ? L("停止中…", "Stopping…") : L("停止", "Stop")}
</Button>
)}
<Button
size="sm"
variant="outline"
className="h-7 gap-1 text-xs"
disabled={busy !== ""}
onClick={() => {
setClearWorkspace(false);
setRecreateOpen(true);
}}
>
<RotateCcwIcon className="size-3.5" />
{busy === "recreate" ? L("重建中…", "Recreating…") : L("重建", "Recreate")}
</Button>
{exists ? (
<Button
size="icon-sm"
variant="ghost"
className="h-7 w-7 text-destructive hover:text-destructive"
disabled={busy !== ""}
onClick={() => setRemoveOpen(true)}
title={L("删除容器", "Delete container")}
>
<Trash2Icon className="size-3.5" />
</Button>
) : null}
<Button
size="icon-sm"
variant="ghost"
className="h-7 w-7"
disabled={loading}
onClick={() => void fetchInfo(true)}
title={L("刷新", "Refresh")}
>
<RefreshCwIcon className={`size-3.5 ${loading ? "animate-spin" : ""}`} />
</Button>
</div>
<div className="flex justify-end border-t pt-2">
<Link
href="/system/sandbox"
className="inline-flex items-center gap-1 text-[11px] text-muted-foreground hover:text-foreground"
>
{L("前往沙箱容器管理", "All Sandbox Containers")}
<ExternalLinkIcon className="size-3" />
</Link>
</div>
</PopoverContent>
</Popover>
<AlertDialog open={recreateOpen} onOpenChange={setRecreateOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{L("重建对话沙箱容器", "Recreate Chat Sandbox")}</AlertDialogTitle>
<AlertDialogDescription>
{L(
"确定销毁当前对话的旧容器并按最新镜像与资源配额重新创建启动吗?",
"Replace this chat's sandbox container with a fresh one using the latest image and limits?",
)}
</AlertDialogDescription>
</AlertDialogHeader>
<div className="flex items-start gap-2.5 rounded-md border bg-muted/30 p-3 text-xs">
<Checkbox
id="chat-sandbox-recreate-wipe"
checked={clearWorkspace}
onCheckedChange={(v) => setClearWorkspace(Boolean(v))}
className="mt-0.5"
/>
<Label htmlFor="chat-sandbox-recreate-wipe" className="block cursor-pointer space-y-0.5 font-normal">
<div className="font-medium text-foreground">
{L("同时清空工作区文件 (/workspace)", "Also clear workspace files (/workspace)")}
</div>
<div className="text-muted-foreground">
{L(
"默认保留本对话上传与生成的文件;勾选后将清空 /workspace 下所有文件。",
"Session files are preserved by default. Check to wipe /workspace.",
)}
</div>
</Label>
</div>
<AlertDialogFooter>
<AlertDialogCancel>{L("取消", "Cancel")}</AlertDialogCancel>
<AlertDialogAction onClick={() => void executeRecreate()}>
{clearWorkspace ? L("清空并重建", "Wipe & Recreate") : L("确认重建", "Recreate")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
<AlertDialog open={removeOpen} onOpenChange={setRemoveOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{L("删除对话沙箱容器", "Delete Chat Sandbox")}</AlertDialogTitle>
<AlertDialogDescription>
{L(
"确定删除该对话的沙箱容器吗?宿主机工作区文件会保留,后续调用工具时将自动重新创建。",
"Remove this chat's sandbox container? Host workspace files will be preserved.",
)}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>{L("取消", "Cancel")}</AlertDialogCancel>
<AlertDialogAction
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
onClick={() => void executeRemove()}
>
{L("确认删除", "Delete")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</>
);
}
+2
View File
@@ -64,6 +64,7 @@ import { isBtwCommand } from "@/lib/side-questions";
import type { Activity, Agent, ChatAttachment, Conversation, LLMProfile } from "@/lib/types";
import { cn } from "@/lib/utils";
import { SessionSandboxControl } from "./_components/session-sandbox-control";
// fmtBytes renders a human file size for attachment chips (mirrors transcript.tsx).
function fmtBytes(n: number): string {
if (n >= 1 << 20) return `${(n / (1 << 20)).toFixed(1)} MB`;
@@ -824,6 +825,7 @@ function ChatView({
)}
{running && <LiveBadge />}
<SideQuestionButton side={side} />
<SessionSandboxControl conversationId={conv.id} running={running} />
<div className="text-muted-foreground ml-auto flex min-w-0 max-w-full items-center justify-end gap-x-3 gap-y-1 text-xs max-sm:w-full max-sm:flex-wrap">
{tokenTotal.turns > 0 && (
<span title={translate("overview.roundsHint")} className="tabular-nums">
@@ -0,0 +1,431 @@
"use client";
import * as React from "react";
import Link from "next/link";
import {
BoxIcon,
ExternalLinkIcon,
PlayIcon,
RefreshCwIcon,
RotateCcwIcon,
SquareIcon,
Trash2Icon,
} from "lucide-react";
import { toast } from "sonner";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Label } from "@/components/ui/label";
import {
Popover,
PopoverContent,
PopoverDescription,
PopoverHeader,
PopoverTitle,
PopoverTrigger,
} from "@/components/ui/popover";
import { useLiveTranslation } from "@/i18n/use-live-translation";
import { api } from "@/lib/api";
import type { SandboxContainerInfo, Task } from "@/lib/types";
function fmtBytes(n?: number): string {
if (!n || n <= 0) return "0 B";
if (n >= 1 << 30) return `${(n / (1 << 30)).toFixed(2)} GiB`;
if (n >= 1 << 20) return `${(n / (1 << 20)).toFixed(1)} MiB`;
if (n >= 1 << 10) return `${(n / (1 << 10)).toFixed(1)} KiB`;
return `${n} B`;
}
function fmtUptime(startedAt?: string): string {
if (!startedAt) return "-";
const ts = Date.parse(startedAt);
if (Number.isNaN(ts)) return "-";
const sec = Math.max(0, Math.floor((Date.now() - ts) / 1000));
if (sec < 60) return `${sec}s`;
const min = Math.floor(sec / 60);
if (min < 60) return `${min}m ${sec % 60}s`;
const hr = Math.floor(min / 60);
if (hr < 24) return `${hr}h ${min % 60}m`;
return `${Math.floor(hr / 24)}d ${hr % 24}h`;
}
export function TaskSandboxControl({ task, onTaskUpdated }: { task: Task; onTaskUpdated: () => void }) {
const { i18n } = useLiveTranslation();
const isEn = i18n.language.startsWith("en");
const L = (zh: string, en: string) => (isEn ? en : zh);
const [open, setOpen] = React.useState(false);
const [info, setInfo] = React.useState<SandboxContainerInfo | null>(null);
const [loading, setLoading] = React.useState(false);
const [busy, setBusy] = React.useState<"" | "start" | "stop" | "recreate" | "remove">("");
const [recreateOpen, setRecreateOpen] = React.useState(false);
const [clearWorkspace, setClearWorkspace] = React.useState(false);
const [removeOpen, setRemoveOpen] = React.useState(false);
const fetchInfo = React.useCallback(
async (withStats: boolean) => {
setLoading(true);
try {
const res = await api.taskSandbox(task.id, withStats);
setInfo(res);
} catch {
// Ignore transient poll errors; detail popover lets user retry.
} finally {
setLoading(false);
}
},
[task.id],
);
React.useEffect(() => {
void fetchInfo(false);
}, [fetchInfo]);
React.useEffect(() => {
if (!open) return;
void fetchInfo(true);
}, [open, fetchInfo]);
// Hide completely when running in local (non-Docker) mode.
if (!info || info.state === "local") {
return null;
}
const running = info.state === "running";
const exists = info.state !== "missing";
const taskRunning = task.status === "running" && !task.paused;
const stateLabel = (() => {
switch (info.state) {
case "running":
return L("沙箱运行中", "Sandbox Running");
case "exited":
return L("沙箱已停止", "Sandbox Stopped");
case "missing":
return L("沙箱未创建", "Sandbox Not Created");
case "error":
return L("沙箱异常", "Sandbox Error");
default:
return info.state;
}
})();
const handleStart = async () => {
setBusy("start");
try {
const res = await api.startTaskSandbox(task.id);
setInfo(res);
toast.success(L("沙箱容器已启动", "Sandbox container started"));
} catch (e) {
toast.error(e instanceof Error ? e.message : String(e));
} finally {
setBusy("");
}
};
const handleStop = async () => {
if (taskRunning) {
const ok = window.confirm(
L(
"当前任务仍在运行,停止容器会同时暂停该任务。确定继续吗?",
"This task is running. Stopping its container will pause the task. Continue?",
),
);
if (!ok) return;
}
setBusy("stop");
try {
const res = await api.stopTaskSandbox(task.id, taskRunning);
setInfo(res);
toast.success(L("沙箱容器已停止(内存已释放)", "Sandbox container stopped"));
if (taskRunning) onTaskUpdated();
} catch (e) {
toast.error(e instanceof Error ? e.message : String(e));
} finally {
setBusy("");
}
};
const executeRecreate = async () => {
const wipe = clearWorkspace;
setRecreateOpen(false);
setClearWorkspace(false);
setBusy("recreate");
try {
const res = await api.recreateTaskSandbox(task.id, {
pause_task: taskRunning,
clear_workspace: wipe,
});
setInfo(res);
toast.success(
wipe
? L("沙箱容器已重建并清空工作区", "Sandbox recreated with clean workspace")
: L("沙箱容器已重建(工作区文件已保留)", "Sandbox container recreated"),
);
if (taskRunning) onTaskUpdated();
} catch (e) {
toast.error(e instanceof Error ? e.message : String(e));
} finally {
setBusy("");
}
};
const executeRemove = async () => {
setRemoveOpen(false);
setBusy("remove");
try {
await api.removeSandboxContainer("task", task.id);
await fetchInfo(false);
toast.success(L("沙箱容器已删除(工作区文件已保留)", "Sandbox container removed"));
if (taskRunning) onTaskUpdated();
} catch (e) {
toast.error(e instanceof Error ? e.message : String(e));
} finally {
setBusy("");
}
};
return (
<>
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button size="sm" variant="outline" className="h-7 gap-1.5 px-2 text-xs">
<BoxIcon className="size-3.5" />
<span
className={`size-1.5 rounded-full ${
running ? "bg-emerald-500" : info.state === "error" ? "bg-red-500" : "bg-muted-foreground/50"
}`}
/>
<span className="hidden sm:inline">{stateLabel}</span>
</Button>
</PopoverTrigger>
<PopoverContent align="end" className="w-80 space-y-3 text-xs">
<PopoverHeader>
<PopoverTitle className="flex items-center justify-between text-sm">
<span className="flex items-center gap-1.5">
<BoxIcon className="size-4" />
{L("任务隔离沙箱", "Task Sandbox")}
</span>
<Badge variant={running ? "default" : "secondary"}>{info.state}</Badge>
</PopoverTitle>
<PopoverDescription className="text-xs">
{L(
"该任务的所有命令、脚本与浏览器均在此隔离容器内运行。",
"All commands, scripts, and browser actions for this task run inside this isolated container.",
)}
</PopoverDescription>
</PopoverHeader>
<div className="space-y-1.5 rounded-md border bg-muted/40 p-2.5 font-mono text-[11px]">
<div className="flex justify-between gap-2">
<span className="text-muted-foreground">{L("容器", "Container")}</span>
<span className="truncate">{info.short_id || "-"}</span>
</div>
<div className="flex justify-between gap-2">
<span className="text-muted-foreground">{L("镜像", "Image")}</span>
<span className="truncate" title={info.image}>
{info.image}
</span>
</div>
<div className="flex justify-between gap-2">
<span className="text-muted-foreground">{L("网络", "Network")}</span>
<span className="truncate">{info.network || "-"}</span>
</div>
{info.runtime ? (
<div className="flex justify-between gap-2">
<span className="text-muted-foreground">{L("运行时", "Runtime")}</span>
<span>{info.runtime}</span>
</div>
) : null}
<div className="flex justify-between gap-2">
<span className="text-muted-foreground">{L("活跃执行", "Active runs")}</span>
<span>{info.active_runs}</span>
</div>
{running ? (
<>
<div className="flex justify-between gap-2">
<span className="text-muted-foreground">{L("运行时长", "Uptime")}</span>
<span>{fmtUptime(info.started_at)}</span>
</div>
<div className="flex justify-between gap-2">
<span className="text-muted-foreground">CPU</span>
<span>{(info.cpu_percent ?? 0).toFixed(1)}%</span>
</div>
<div className="flex justify-between gap-2">
<span className="text-muted-foreground">{L("内存", "Memory")}</span>
<span>
{fmtBytes(info.mem_usage_bytes)}
{info.mem_limit_bytes ? ` / ${fmtBytes(info.mem_limit_bytes)}` : ""}
</span>
</div>
{info.pids_current != null ? (
<div className="flex justify-between gap-2">
<span className="text-muted-foreground">PIDs</span>
<span>{info.pids_current}</span>
</div>
) : null}
</>
) : null}
{info.error ? <p className="text-destructive break-all">{info.error}</p> : null}
</div>
<div className="flex flex-wrap items-center gap-1.5">
{!running ? (
<Button
size="sm"
variant="default"
className="h-7 flex-1 gap-1 text-xs"
disabled={busy !== ""}
onClick={() => void handleStart()}
>
<PlayIcon className="size-3.5" />
{busy === "start" ? L("启动中…", "Starting…") : L("启动", "Start")}
</Button>
) : (
<Button
size="sm"
variant="outline"
className="h-7 flex-1 gap-1 text-xs"
disabled={busy !== ""}
onClick={() => void handleStop()}
>
<SquareIcon className="size-3.5" />
{busy === "stop" ? L("停止中…", "Stopping…") : L("停止", "Stop")}
</Button>
)}
<Button
size="sm"
variant="outline"
className="h-7 gap-1 text-xs"
disabled={busy !== ""}
onClick={() => {
setClearWorkspace(false);
setRecreateOpen(true);
}}
>
<RotateCcwIcon className="size-3.5" />
{busy === "recreate" ? L("重建中…", "Recreating…") : L("重建", "Recreate")}
</Button>
{exists ? (
<Button
size="icon-sm"
variant="ghost"
className="h-7 w-7 text-destructive hover:text-destructive"
disabled={busy !== ""}
onClick={() => setRemoveOpen(true)}
title={L("删除容器", "Delete container")}
>
<Trash2Icon className="size-3.5" />
</Button>
) : null}
<Button
size="icon-sm"
variant="ghost"
className="h-7 w-7"
disabled={loading}
onClick={() => void fetchInfo(true)}
title={L("刷新", "Refresh")}
>
<RefreshCwIcon className={`size-3.5 ${loading ? "animate-spin" : ""}`} />
</Button>
</div>
<div className="flex justify-end border-t pt-2">
<Link
href="/system/sandbox"
className="inline-flex items-center gap-1 text-[11px] text-muted-foreground hover:text-foreground"
>
{L("前往沙箱容器管理", "All Sandbox Containers")}
<ExternalLinkIcon className="size-3" />
</Link>
</div>
</PopoverContent>
</Popover>
<AlertDialog open={recreateOpen} onOpenChange={setRecreateOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{L("重建任务沙箱容器", "Recreate Task Sandbox")}</AlertDialogTitle>
<AlertDialogDescription>
{taskRunning
? L(
"重建容器会暂停当前任务并销毁旧容器,按最新镜像与资源配额重新创建启动。",
"Recreating will pause the running task, destroy the old container, and start a fresh one with the latest image and limits.",
)
: L(
"确定销毁旧容器并按最新镜像与资源配额重新创建启动吗?",
"Replace this sandbox container with a fresh one using the latest image and limits?",
)}
</AlertDialogDescription>
</AlertDialogHeader>
<div className="flex items-start gap-2.5 rounded-md border bg-muted/30 p-3 text-xs">
<Checkbox
id="task-sandbox-recreate-wipe"
checked={clearWorkspace}
onCheckedChange={(v) => setClearWorkspace(Boolean(v))}
className="mt-0.5"
/>
<Label htmlFor="task-sandbox-recreate-wipe" className="block cursor-pointer space-y-0.5 font-normal">
<div className="font-medium text-foreground">
{L("同时清空工作区文件 (/workspace)", "Also clear workspace files (/workspace)")}
</div>
<div className="text-muted-foreground">
{L(
"默认保留任务工作区文件;勾选后将清空 /workspace 下所有产物与脚本。",
"Workspace files are preserved by default. Check to wipe /workspace.",
)}
</div>
</Label>
</div>
<AlertDialogFooter>
<AlertDialogCancel>{L("取消", "Cancel")}</AlertDialogCancel>
<AlertDialogAction onClick={() => void executeRecreate()}>
{clearWorkspace ? L("清空并重建", "Wipe & Recreate") : L("确认重建", "Recreate")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
<AlertDialog open={removeOpen} onOpenChange={setRemoveOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{L("删除任务沙箱容器", "Delete Task Sandbox")}</AlertDialogTitle>
<AlertDialogDescription>
{taskRunning
? L(
"任务仍在运行,删除容器会同时暂停任务并移除容器(工作区文件保留,下次执行自动重建)。",
"This task is running. Removing the container will pause the task (workspace files are preserved).",
)
: L(
"确定删除该任务的沙箱容器吗?宿主机工作区文件会保留,后续执行将按需重新创建。",
"Remove this task's sandbox container? Host workspace files will be preserved.",
)}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>{L("取消", "Cancel")}</AlertDialogCancel>
<AlertDialogAction
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
onClick={() => void executeRemove()}
>
{L("确认删除", "Delete")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</>
);
}
@@ -55,6 +55,7 @@ import { OverviewTab } from "./_tabs/overview-tab";
import { ReportTab } from "./_tabs/report-tab";
import { RetestsTab } from "./_tabs/retests-tab";
import { SessionsTab } from "./_tabs/sessions-tab";
import { TaskSandboxControl } from "./_components/task-sandbox-control";
const TABS = (ui: UITranslate) => [
{ value: "sessions", label: ui("screen.a63280253f17d4") },
@@ -498,6 +499,7 @@ function TaskDetailInner() {
</code>
<Separator orientation="vertical" className="mx-1 hidden h-4 sm:block" />
<TaskLLMControl task={task} profiles={profiles} onUpdated={load} />
<TaskSandboxControl task={task} onTaskUpdated={load} />
<StatusBadge
stopReason={task.stop_reason}
domain={terminal ? "task" : "engine"}
+947
View File
@@ -0,0 +1,947 @@
"use client";
import * as React from "react";
import Link from "next/link";
import {
ActivityIcon,
BoxIcon,
CpuIcon,
ExternalLinkIcon,
HardDriveIcon,
PlayIcon,
RefreshCwIcon,
RotateCcwIcon,
SearchIcon,
Settings2Icon,
SquareIcon,
Trash2Icon,
} from "lucide-react";
import { toast } from "sonner";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Progress } from "@/components/ui/progress";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { useLiveTranslation } from "@/i18n/use-live-translation";
import { api } from "@/lib/api";
import type { SandboxContainerInfo, SandboxGlobalStatus } from "@/lib/types";
function fmtBytes(n?: number): string {
if (!n || n <= 0) return "0 B";
if (n >= 1 << 30) return `${(n / (1 << 30)).toFixed(2)} GiB`;
if (n >= 1 << 20) return `${(n / (1 << 20)).toFixed(1)} MiB`;
if (n >= 1 << 10) return `${(n / (1 << 10)).toFixed(1)} KiB`;
return `${n} B`;
}
function ownerHref(c: SandboxContainerInfo): string | null {
if (c.scope === "task" && c.owner_id) {
return `/function/tasks/detail?id=${encodeURIComponent(c.owner_id)}`;
}
if (c.scope === "session" && c.owner_id) {
const num = c.owner_id.startsWith("conv-") ? c.owner_id.slice(5) : c.owner_id;
return num ? `/chat?c=${encodeURIComponent(num)}` : "/chat";
}
return null;
}
function fmtCreatedAt(iso?: string): string {
if (!iso) return "-";
const d = new Date(iso);
if (Number.isNaN(d.getTime())) return iso;
return d.toLocaleString(undefined, {
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
});
}
export default function SandboxPage() {
const { i18n } = useLiveTranslation();
const isEn = i18n.language.startsWith("en");
const L = (zh: string, en: string) => (isEn ? en : zh);
const [status, setStatus] = React.useState<SandboxGlobalStatus | null>(null);
const [loading, setLoading] = React.useState(false);
const [autoRefresh, setAutoRefresh] = React.useState(true);
const [saving, setSaving] = React.useState(false);
const [pruning, setPruning] = React.useState(false);
const [busyKey, setBusyKey] = React.useState<string>("");
// Filters
const [scopeFilter, setScopeFilter] = React.useState<"all" | "task" | "session">("all");
const [stateFilter, setStateFilter] = React.useState<"all" | "running" | "stopped">("all");
const [query, setQuery] = React.useState("");
// Config form state
const [image, setImage] = React.useState("");
const [memoryMB, setMemoryMB] = React.useState("2048");
const [cpus, setCpus] = React.useState("2");
const [pidsLimit, setPidsLimit] = React.useState("256");
const [shmSizeMB, setShmSizeMB] = React.useState("512");
const [runtime, setRuntime] = React.useState("");
const [autoStop, setAutoStop] = React.useState(true);
const [idleMin, setIdleMin] = React.useState("20");
const formDirtyRef = React.useRef(false);
// Dialog states
const [recreateTarget, setRecreateTarget] = React.useState<SandboxContainerInfo | null>(null);
const [recreateClearWorkspace, setRecreateClearWorkspace] = React.useState(false);
const [removeTarget, setRemoveTarget] = React.useState<SandboxContainerInfo | null>(null);
const [stopTarget, setStopTarget] = React.useState<SandboxContainerInfo | null>(null);
const applyStatus = React.useCallback((s: SandboxGlobalStatus, forceForm = false) => {
setStatus(s);
if (forceForm || !formDirtyRef.current) {
setImage(s.image || "");
setMemoryMB(String(s.memory_mb || 2048));
setCpus(String(s.cpus || 2));
setPidsLimit(String(s.pids_limit || 256));
setShmSizeMB(String(s.shm_size_mb || 512));
setRuntime(s.runtime || "");
setAutoStop(s.auto_stop_on_complete !== false);
setIdleMin(String(s.session_idle_minutes || 20));
}
}, []);
const loadSeqRef = React.useRef(0);
const load = React.useCallback(
async (silent = false, forceForm = false, progressive = false) => {
const seq = ++loadSeqRef.current;
if (!silent) setLoading(true);
try {
// Fast path: fetch container list + cached stats immediately (~10ms) so
// opening the page never blocks on Docker's ~1s live CPU sampling.
const fast = await api.sandboxStatus(!progressive);
if (seq !== loadSeqRef.current) return;
applyStatus(fast, forceForm);
if (!silent) setLoading(false);
if (progressive && fast.enabled && fast.containers.some((c) => c.state === "running")) {
void api
.sandboxStatus(true)
.then((fresh) => {
if (seq === loadSeqRef.current) {
applyStatus(fresh, false);
}
})
.catch(() => {
// ignore transient background stats hydration errors
});
}
} catch (e) {
if (seq === loadSeqRef.current && !silent) {
toast.error(e instanceof Error ? e.message : String(e));
}
} finally {
if (seq === loadSeqRef.current && !silent) setLoading(false);
}
},
[applyStatus],
);
React.useEffect(() => {
void load(false, true, true);
}, [load]);
React.useEffect(() => {
if (!autoRefresh) return;
const timer = window.setInterval(() => {
if (document.visibilityState === "visible") {
void load(true, false, false);
}
}, 8000);
return () => window.clearInterval(timer);
}, [autoRefresh, load]);
const containers = status?.containers ?? [];
const runningContainers = containers.filter((c) => c.state === "running");
const stoppedContainers = containers.filter((c) => c.state !== "running");
const totalMemUsage = runningContainers.reduce((acc, c) => acc + (c.mem_usage_bytes ?? 0), 0);
const totalCpu = runningContainers.reduce((acc, c) => acc + (c.cpu_percent ?? 0), 0);
const totalActiveRuns = containers.reduce((acc, c) => acc + (c.active_runs ?? 0), 0);
const filtered = React.useMemo(() => {
const q = query.trim().toLowerCase();
return containers.filter((c) => {
if (scopeFilter !== "all" && c.scope !== scopeFilter) return false;
if (stateFilter === "running" && c.state !== "running") return false;
if (stateFilter === "stopped" && c.state === "running") return false;
if (q) {
const hay =
`${c.scope}:${c.owner_id} ${c.owner_title ?? ""} ${c.name} ${c.short_id ?? ""} ${c.image}`.toLowerCase();
if (!hay.includes(q)) return false;
}
return true;
});
}, [containers, scopeFilter, stateFilter, query]);
const containerKey = (c: SandboxContainerInfo) => `${c.scope}:${c.owner_id}`;
const handleStart = async (c: SandboxContainerInfo) => {
const key = containerKey(c);
setBusyKey(key);
try {
await api.startSandboxContainer(c.scope, c.owner_id);
toast.success(L(`容器 ${key} 已启动`, `Container ${key} started`));
await load(true);
} catch (e) {
toast.error(e instanceof Error ? e.message : String(e));
} finally {
setBusyKey("");
}
};
const executeStop = async (c: SandboxContainerInfo) => {
const key = containerKey(c);
setBusyKey(key);
try {
await api.stopSandboxContainer(c.scope, c.owner_id);
toast.success(L(`容器 ${key} 已停止(内存已释放)`, `Container ${key} stopped`));
await load(true);
} catch (e) {
toast.error(e instanceof Error ? e.message : String(e));
} finally {
setBusyKey("");
}
};
const handleStopClick = (c: SandboxContainerInfo) => {
if (c.task_running) {
setStopTarget(c);
} else {
void executeStop(c);
}
};
const executeRecreate = async () => {
if (!recreateTarget) return;
const c = recreateTarget;
const clearWs = recreateClearWorkspace;
setRecreateTarget(null);
setRecreateClearWorkspace(false);
const key = containerKey(c);
setBusyKey(key);
try {
await api.recreateSandboxContainer(c.scope, c.owner_id, {
pause_task: Boolean(c.task_running),
clear_workspace: clearWs,
});
toast.success(
clearWs
? L(`容器 ${key} 已重建并清空工作区`, `Container ${key} recreated with clean workspace`)
: L(`容器 ${key} 已重建(工作区文件已保留)`, `Container ${key} recreated`),
);
await load(true);
} catch (e) {
toast.error(e instanceof Error ? e.message : String(e));
} finally {
setBusyKey("");
}
};
const executeRemove = async () => {
if (!removeTarget) return;
const c = removeTarget;
setRemoveTarget(null);
const key = containerKey(c);
setBusyKey(key);
try {
await api.removeSandboxContainer(c.scope, c.owner_id);
toast.success(L(`容器 ${key} 已删除`, `Container ${key} removed`));
await load(true);
} catch (e) {
toast.error(e instanceof Error ? e.message : String(e));
} finally {
setBusyKey("");
}
};
const handlePrune = async () => {
setPruning(true);
try {
const r = await api.pruneSandboxContainers();
toast.success(L(`已清理 ${r.removed} 个已停止的沙箱容器`, `Removed ${r.removed} stopped sandbox container(s)`));
await load(true);
} catch (e) {
toast.error(e instanceof Error ? e.message : String(e));
} finally {
setPruning(false);
}
};
const handleSaveSettings = async () => {
setSaving(true);
try {
const updated = await api.updateSandboxSettings({
image: image.trim(),
memory_mb: Number(memoryMB) || 2048,
cpus: Number(cpus) || 2,
pids_limit: Number(pidsLimit) || 256,
shm_size_mb: Number(shmSizeMB) || 512,
runtime: runtime.trim(),
auto_stop_on_complete: autoStop,
session_idle_minutes: Number(idleMin) || 20,
});
formDirtyRef.current = false;
applyStatus(updated, true);
toast.success(L("沙箱配置已保存(新创建或重建的容器生效)", "Sandbox settings saved"));
} catch (e) {
toast.error(e instanceof Error ? e.message : String(e));
} finally {
setSaving(false);
}
};
const scopeBadge = (scope: string) => {
if (scope === "task") return <Badge variant="outline">{L("任务", "Task")}</Badge>;
if (scope === "session") return <Badge variant="secondary">{L("对话", "Chat")}</Badge>;
return <Badge variant="secondary">{scope}</Badge>;
};
return (
<div className="flex min-w-0 w-full flex-1 flex-col gap-4 md:gap-6">
{/* Header */}
<div className="flex min-w-0 flex-wrap items-start justify-between gap-3">
<div className="min-w-0 space-y-1">
<div className="flex flex-wrap items-center gap-2">
<h1 className="flex items-center gap-2 font-semibold text-xl tracking-tight">
<BoxIcon className="size-5" />
{L("沙箱容器", "Sandbox Containers")}
</h1>
{status ? (
<Badge variant={status.enabled ? (status.available ? "default" : "destructive") : "secondary"}>
{status.enabled
? status.available
? `Docker · ${status.runtime || "runc"}`
: L("Docker 不可用", "Docker Unavailable")
: L("本地模式", "Local Mode")}
</Badge>
) : (
<Badge variant="secondary">{L("加载中…", "Loading…")}</Badge>
)}
</div>
<p className="text-muted-foreground text-sm">
{!status
? L("正在读取沙箱运行状态与托管容器…", "Loading sandbox status and managed containers…")
: status.enabled
? L(
`统一管理所有任务与对话的隔离容器生命周期与资源占用(隔离网络:${status.network},已禁用容器间互通)。`,
`Manage lifecycle and resource usage for isolated task and chat containers (network: ${status.network}, ICC disabled).`,
)
: L(
"当前为本地执行模式。部署时配置 ARTEX_SANDBOX_MODE=docker 即可启用任务与对话级容器隔离。",
"Running in local execution mode. Set ARTEX_SANDBOX_MODE=docker to enable container isolation.",
)}
</p>
</div>
<div className="flex flex-wrap items-center gap-2">
{status?.enabled ? (
<>
<div className="flex items-center gap-1.5 rounded-md border px-2.5 py-1.5 text-xs">
<Switch id="sandbox-auto-refresh" checked={autoRefresh} onCheckedChange={setAutoRefresh} />
<Label
htmlFor="sandbox-auto-refresh"
className="cursor-pointer font-normal text-muted-foreground text-xs"
>
{L("自动刷新", "Auto-refresh")}
</Label>
</div>
<Button
size="sm"
variant="outline"
disabled={pruning || stoppedContainers.length === 0}
onClick={() => void handlePrune()}
>
<Trash2Icon className="mr-1.5 size-3.5" />
{pruning
? L("清理中…", "Pruning…")
: L(`清理已停止 (${stoppedContainers.length})`, `Prune Stopped (${stoppedContainers.length})`)}
</Button>
</>
) : null}
<Button size="sm" variant="outline" disabled={loading} onClick={() => void load(false, false, true)}>
<RefreshCwIcon className={`mr-1.5 size-3.5 ${loading ? "animate-spin" : ""}`} />
{L("刷新", "Refresh")}
</Button>
</div>
</div>
{status?.error ? (
<div className="rounded-lg border border-destructive/40 bg-destructive/10 px-4 py-3 text-sm text-destructive">
{status.error}
</div>
) : null}
{/* Summary KPI cards */}
{status?.enabled ? (
<div className="grid min-w-0 grid-cols-2 gap-3 lg:grid-cols-4">
<Card className="min-w-0">
<CardHeader className="pb-2">
<CardDescription className="flex items-center gap-1.5 text-xs">
<ActivityIcon className="size-3.5 shrink-0 text-emerald-500" />
<span className="truncate">{L("运行中容器", "Running Containers")}</span>
</CardDescription>
<CardTitle className="text-2xl tabular-nums">
{runningContainers.length}
<span className="ml-1.5 font-normal text-muted-foreground text-sm">/ {containers.length}</span>
</CardTitle>
</CardHeader>
</Card>
<Card className="min-w-0">
<CardHeader className="pb-2">
<CardDescription className="flex items-center gap-1.5 text-xs">
<SquareIcon className="size-3.5 shrink-0 text-muted-foreground" />
<span className="truncate">{L("已停止(内存已释放)", "Stopped (Memory Freed)")}</span>
</CardDescription>
<CardTitle className="text-2xl tabular-nums">{stoppedContainers.length}</CardTitle>
</CardHeader>
</Card>
<Card className="min-w-0">
<CardHeader className="pb-2">
<CardDescription className="flex items-center gap-1.5 text-xs">
<HardDriveIcon className="size-3.5 shrink-0 text-blue-500" />
<span className="truncate">{L("运行容器总内存", "Active Memory Usage")}</span>
</CardDescription>
<CardTitle className="text-2xl tabular-nums">{fmtBytes(totalMemUsage)}</CardTitle>
<div className="truncate text-[11px] text-muted-foreground">
{L(`单容器上限 ${status.memory_mb} MiB`, `Cap ${status.memory_mb} MiB / container`)}
</div>
</CardHeader>
</Card>
<Card className="min-w-0">
<CardHeader className="pb-2">
<CardDescription className="flex items-center gap-1.5 text-xs">
<CpuIcon className="size-3.5 shrink-0 text-amber-500" />
<span className="truncate">{L("总 CPU / 活跃执行", "Total CPU / Active Runs")}</span>
</CardDescription>
<CardTitle className="text-2xl tabular-nums">{totalCpu.toFixed(1)}%</CardTitle>
<div className="truncate text-[11px] text-muted-foreground">
{L(`活跃执行 ${totalActiveRuns}`, `${totalActiveRuns} active run(s)`)}
</div>
</CardHeader>
</Card>
</div>
) : null}
{status?.enabled ? (
<Tabs defaultValue="containers" className="min-w-0 w-full space-y-4">
<TabsList>
<TabsTrigger value="containers" className="gap-1.5">
<BoxIcon className="size-3.5" />
{L(`托管容器 (${containers.length})`, `Containers (${containers.length})`)}
</TabsTrigger>
<TabsTrigger value="settings" className="gap-1.5">
<Settings2Icon className="size-3.5" />
{L("全局配额与策略", "Limits & Policy")}
</TabsTrigger>
</TabsList>
{/* Tab 1: Container Lifecycle Management */}
<TabsContent value="containers" className="min-w-0 space-y-3">
<div className="flex flex-wrap items-center gap-2">
<div className="relative min-w-[220px] flex-1">
<Input
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder={L(
"搜索任务名、归属 ID、容器 ID 或镜像…",
"Search task title, owner ID, container ID, or image…",
)}
className="h-8 pl-8 text-xs"
/>
</div>
<Select value={scopeFilter} onValueChange={(v) => setScopeFilter(v as "all" | "task" | "session")}>
<SelectTrigger className="h-8 w-32 text-xs">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">{L("全部类型", "All Scopes")}</SelectItem>
<SelectItem value="task">{L("仅任务容器", "Tasks Only")}</SelectItem>
<SelectItem value="session">{L("仅对话容器", "Chats Only")}</SelectItem>
</SelectContent>
</Select>
<Select value={stateFilter} onValueChange={(v) => setStateFilter(v as "all" | "running" | "stopped")}>
<SelectTrigger className="h-8 w-32 text-xs">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">{L("全部状态", "All States")}</SelectItem>
<SelectItem value="running">{L("运行中", "Running")}</SelectItem>
<SelectItem value="stopped">{L("已停止", "Stopped")}</SelectItem>
</SelectContent>
</Select>
</div>
<div className="min-w-0 w-full overflow-x-auto rounded-lg border bg-card">
<Table>
<TableHeader>
<TableRow>
<TableHead>{L("归属与容器", "Owner & Container")}</TableHead>
<TableHead>{L("状态与时长", "State & Uptime")}</TableHead>
<TableHead className="min-w-[160px]">{L("实时资源", "Resources")}</TableHead>
<TableHead>{L("镜像与创建时间", "Image & Created")}</TableHead>
<TableHead className="text-right">{L("生命周期操作", "Lifecycle")}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{filtered.length === 0 ? (
<TableRow>
<TableCell colSpan={5} className="py-10 text-center text-sm text-muted-foreground">
{containers.length === 0
? L(
"暂无沙箱容器(任务或对话执行命令/脚本/浏览器时会自动按需创建)",
"No sandbox containers yet (created on demand when tasks or chats execute tools)",
)
: L("没有符合当前筛选条件的容器", "No containers match the current filter")}
</TableCell>
</TableRow>
) : (
filtered.map((c) => {
const running = c.state === "running";
const key = containerKey(c);
const isBusy = busyKey === key;
const href = ownerHref(c);
const memLimit = c.mem_limit_bytes || (status.memory_mb ? status.memory_mb * 1024 * 1024 : 0);
const memPct =
running && memLimit > 0
? Math.min(100, Math.round(((c.mem_usage_bytes ?? 0) / memLimit) * 100))
: 0;
return (
<TableRow key={c.container_id || c.name}>
<TableCell>
<div className="space-y-1">
<div className="flex items-center gap-1.5">
{scopeBadge(c.scope)}
{href ? (
<Link
href={href}
className="inline-flex items-center gap-1 font-mono text-xs font-medium hover:underline"
>
{c.scope === "task" ? `#${c.owner_id}` : c.owner_id}
<ExternalLinkIcon className="size-3 text-muted-foreground" />
</Link>
) : (
<span className="font-mono text-xs font-medium">{c.owner_id}</span>
)}
{c.task_running ? (
<Badge variant="default" className="h-4 px-1.5 text-[10px]">
{L("任务运行中", "Task Active")}
</Badge>
) : null}
</div>
{c.owner_title ? (
<div
className="max-w-[200px] truncate text-xs text-muted-foreground"
title={c.owner_title}
>
{c.owner_title}
</div>
) : null}
<div
className="max-w-[200px] truncate font-mono text-[11px] text-muted-foreground"
title={c.name}
>
{c.short_id || "-"} · {c.name}
</div>
</div>
</TableCell>
<TableCell>
<div className="space-y-1">
<div className="flex items-center gap-1.5">
<span
className={`size-2 rounded-full ${
running
? "bg-emerald-500"
: c.state === "error"
? "bg-red-500"
: "bg-muted-foreground/50"
}`}
/>
<Badge variant={running ? "default" : "secondary"} className="text-[11px]">
{running ? L("运行中", "running") : c.state}
</Badge>
</div>
<div className="text-[11px] text-muted-foreground">{c.status_text || c.state}</div>
<div className="font-mono text-[11px] text-muted-foreground">
{L("活跃执行", "active")}={c.active_runs}
</div>
</div>
</TableCell>
<TableCell>
{running ? (
<div className="space-y-1.5 font-mono text-[11px]">
<div className="flex items-center justify-between gap-2">
<span className="text-muted-foreground">CPU</span>
<span>{(c.cpu_percent ?? 0).toFixed(1)}%</span>
</div>
<div className="space-y-1">
<div className="flex items-center justify-between gap-2">
<span className="text-muted-foreground">MEM</span>
<span>
{fmtBytes(c.mem_usage_bytes)} / {fmtBytes(memLimit)}
</span>
</div>
<Progress value={memPct} className="h-1.5" />
</div>
{c.pids_current != null ? (
<div className="flex items-center justify-between gap-2 text-muted-foreground">
<span>PIDs</span>
<span>
{c.pids_current} / {status.pids_limit}
</span>
</div>
) : null}
</div>
) : (
<span className="text-xs text-muted-foreground">
{L("已释放(容器未运行)", "Freed (stopped)")}
</span>
)}
</TableCell>
<TableCell>
<div className="space-y-1 font-mono text-[11px]">
<div className="max-w-[180px] truncate" title={c.image}>
{c.image}
</div>
<div className="text-muted-foreground">{fmtCreatedAt(c.created_at)}</div>
</div>
</TableCell>
<TableCell className="text-right">
<div className="flex flex-wrap items-center justify-end gap-1.5">
{!running ? (
<Button
size="sm"
variant="default"
className="h-7 gap-1 px-2.5 text-xs"
disabled={isBusy}
onClick={() => void handleStart(c)}
>
<PlayIcon className="size-3" />
{L("启动", "Start")}
</Button>
) : (
<Button
size="sm"
variant="outline"
className="h-7 gap-1 px-2.5 text-xs"
disabled={isBusy}
onClick={() => handleStopClick(c)}
>
<SquareIcon className="size-3" />
{L("停止", "Stop")}
</Button>
)}
<Button
size="sm"
variant="outline"
className="h-7 gap-1 px-2.5 text-xs"
disabled={isBusy}
onClick={() => {
setRecreateClearWorkspace(false);
setRecreateTarget(c);
}}
>
<RotateCcwIcon className="size-3" />
{L("重建", "Recreate")}
</Button>
<Button
size="icon-sm"
variant="ghost"
className="h-7 w-7 text-destructive hover:text-destructive"
disabled={isBusy}
onClick={() => setRemoveTarget(c)}
title={L("删除容器", "Delete container")}
>
<Trash2Icon className="size-3.5" />
</Button>
</div>
</TableCell>
</TableRow>
);
})
)}
</TableBody>
</Table>
</div>
</TabsContent>
{/* Tab 2: Global Sandbox Settings */}
<TabsContent value="settings">
<Card>
<CardHeader>
<CardTitle className="text-base">
{L("默认镜像、资源配额与自动停机策略", "Default Image, Limits & Auto-Stop Policy")}
</CardTitle>
<CardDescription>
{L(
"保存后会持久化到数据库,并对新创建或手动「重建」的容器生效。",
"Persisted to the database and applied to newly created or recreated containers.",
)}
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-1 gap-3 md:grid-cols-3">
<div className="space-y-1">
<Label className="text-xs">{L("沙箱工具镜像", "Sandbox Image")}</Label>
<Input
value={image}
onChange={(e) => {
formDirtyRef.current = true;
setImage(e.target.value);
}}
placeholder="ruoji6/artex-sandbox:latest"
/>
</div>
<div className="space-y-1">
<Label className="text-xs">{L("单容器内存上限 (MiB)", "Memory Limit (MiB)")}</Label>
<Input
type="number"
min={256}
value={memoryMB}
onChange={(e) => {
formDirtyRef.current = true;
setMemoryMB(e.target.value);
}}
/>
</div>
<div className="space-y-1">
<Label className="text-xs">{L("单容器 CPU 核数", "CPU Cores")}</Label>
<Input
type="number"
step="0.5"
min={0.25}
value={cpus}
onChange={(e) => {
formDirtyRef.current = true;
setCpus(e.target.value);
}}
/>
</div>
<div className="space-y-1">
<Label className="text-xs">{L("进程数上限 (PIDs)", "PIDs Limit")}</Label>
<Input
type="number"
min={32}
value={pidsLimit}
onChange={(e) => {
formDirtyRef.current = true;
setPidsLimit(e.target.value);
}}
/>
</div>
<div className="space-y-1">
<Label className="text-xs">{L("共享内存 /dev/shm (MiB)", "Shared Memory (MiB)")}</Label>
<Input
type="number"
min={64}
value={shmSizeMB}
onChange={(e) => {
formDirtyRef.current = true;
setShmSizeMB(e.target.value);
}}
/>
</div>
<div className="space-y-1">
<Label className="text-xs">
{L("容器运行时(留空默认 runc / 可填 runsc)", "Runtime (blank=runc, or runsc)")}
</Label>
<Input
value={runtime}
onChange={(e) => {
formDirtyRef.current = true;
setRuntime(e.target.value);
}}
placeholder="runc / runsc"
/>
</div>
</div>
<div className="flex flex-wrap items-center justify-between gap-3 rounded-md border bg-muted/30 px-3 py-2.5">
<div className="flex items-center gap-3">
<Switch
checked={autoStop}
onCheckedChange={(v) => {
formDirtyRef.current = true;
setAutoStop(v);
}}
/>
<div>
<div className="text-xs font-medium">
{L("任务结束或暂停后自动停止容器", "Auto-stop container on task finish or pause")}
</div>
<div className="text-[11px] text-muted-foreground">
{L(
"释放内存与 CPU,工作区文件保留,恢复任务时自动秒级重启。",
"Frees RAM and CPU while keeping workspace files for fast resume.",
)}
</div>
</div>
</div>
<div className="flex items-center gap-2">
<Label className="text-xs text-muted-foreground">
{L("对话空闲停机(分钟)", "Chat idle stop (min)")}
</Label>
<Input
className="h-8 w-20"
type="number"
min={1}
value={idleMin}
onChange={(e) => {
formDirtyRef.current = true;
setIdleMin(e.target.value);
}}
/>
<Button size="sm" disabled={saving} onClick={() => void handleSaveSettings()}>
{saving ? L("保存中…", "Saving…") : L("保存配置", "Save")}
</Button>
</div>
</div>
</CardContent>
</Card>
</TabsContent>
</Tabs>
) : null}
{/* Stop Running Task Container Dialog */}
<AlertDialog open={Boolean(stopTarget)} onOpenChange={(o) => !o && setStopTarget(null)}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>
{L("确认停止正在运行任务的沙箱容器?", "Stop container for a running task?")}
</AlertDialogTitle>
<AlertDialogDescription>
{stopTarget
? L(
`任务 #${stopTarget.owner_id} 当前正在运行,停止容器 ${stopTarget.short_id || stopTarget.name} 会同时暂停该任务。工作区文件会保留。`,
`Task #${stopTarget.owner_id} is currently running. Stopping container ${stopTarget.short_id || stopTarget.name} will pause the task. Workspace files will be kept.`,
)
: null}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>{L("取消", "Cancel")}</AlertDialogCancel>
<AlertDialogAction
onClick={() => {
if (stopTarget) {
const target = stopTarget;
setStopTarget(null);
void executeStop(target);
}
}}
>
{L("暂停任务并停止容器", "Pause Task & Stop")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
{/* Recreate Container Dialog */}
<AlertDialog open={Boolean(recreateTarget)} onOpenChange={(o) => !o && setRecreateTarget(null)}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{L("重建沙箱容器", "Recreate Sandbox Container")}</AlertDialogTitle>
<AlertDialogDescription>
{recreateTarget
? recreateTarget.task_running
? L(
`将暂停任务 #${recreateTarget.owner_id},销毁旧容器并按最新镜像和配额重新创建。`,
`This will pause task #${recreateTarget.owner_id}, destroy the old container, and create a fresh one with the latest image and limits.`,
)
: L(
`将销毁容器 ${recreateTarget.scope}:${recreateTarget.owner_id} 并按最新镜像和配额重新创建启动。`,
`This will destroy container ${recreateTarget.scope}:${recreateTarget.owner_id} and start a fresh one with the latest image and limits.`,
)
: null}
</AlertDialogDescription>
</AlertDialogHeader>
<div className="flex items-start gap-2.5 rounded-md border bg-muted/30 p-3 text-xs">
<Checkbox
id="sandbox-recreate-wipe"
checked={recreateClearWorkspace}
onCheckedChange={(v) => setRecreateClearWorkspace(Boolean(v))}
className="mt-0.5"
/>
<Label htmlFor="sandbox-recreate-wipe" className="block cursor-pointer space-y-0.5 font-normal">
<div className="font-medium text-foreground">
{L("同时清空工作区文件 (/workspace)", "Also clear workspace files (/workspace)")}
</div>
<div className="text-muted-foreground">
{L(
"默认保留工作区脚本、截图和附件;如怀疑环境被污染可勾选彻底清空。",
"Workspace files are kept by default. Check this to wipe all files inside /workspace.",
)}
</div>
</Label>
</div>
<AlertDialogFooter>
<AlertDialogCancel>{L("取消", "Cancel")}</AlertDialogCancel>
<AlertDialogAction onClick={() => void executeRecreate()}>
{recreateClearWorkspace ? L("清空并重建", "Wipe & Recreate") : L("确认重建", "Recreate")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
{/* Delete Container Dialog */}
<AlertDialog open={Boolean(removeTarget)} onOpenChange={(o) => !o && setRemoveTarget(null)}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{L("删除沙箱容器", "Delete Sandbox Container")}</AlertDialogTitle>
<AlertDialogDescription>
{removeTarget
? removeTarget.task_running
? L(
`任务 #${removeTarget.owner_id} 正在运行,删除容器会同时暂停该任务并销毁容器层(宿主机工作区目录保留,下次执行时将自动新建容器)。`,
`Task #${removeTarget.owner_id} is running. Deleting will pause the task and remove the container (host workspace files are preserved).`,
)
: L(
`确定彻底删除容器 ${removeTarget.scope}:${removeTarget.owner_id}(${removeTarget.short_id || removeTarget.name})吗?宿主机工作区文件会保留,后续执行将按需重新创建。`,
`Remove container ${removeTarget.scope}:${removeTarget.owner_id} (${removeTarget.short_id || removeTarget.name})? Host workspace files are preserved.`,
)
: null}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>{L("取消", "Cancel")}</AlertDialogCancel>
<AlertDialogAction
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
onClick={() => void executeRemove()}
>
{L("确认删除", "Delete")}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
);
}
@@ -0,0 +1,423 @@
"use client";
import * as React from "react";
import Link from "next/link";
import {
BoxIcon,
ExternalLinkIcon,
PlayIcon,
RefreshCwIcon,
RotateCcwIcon,
SquareIcon,
Trash2Icon,
} from "lucide-react";
import { toast } from "sonner";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
import { useLiveTranslation } from "@/i18n/use-live-translation";
import { api } from "@/lib/api";
import type { SandboxContainerInfo, SandboxGlobalStatus } from "@/lib/types";
function fmtBytes(n?: number): string {
if (!n || n <= 0) return "0 B";
if (n >= 1 << 30) return `${(n / (1 << 30)).toFixed(2)} GiB`;
if (n >= 1 << 20) return `${(n / (1 << 20)).toFixed(1)} MiB`;
if (n >= 1 << 10) return `${(n / (1 << 10)).toFixed(1)} KiB`;
return `${n} B`;
}
function ownerHref(c: SandboxContainerInfo): string | null {
if (c.scope === "task" && c.owner_id) {
return `/function/tasks/detail?id=${encodeURIComponent(c.owner_id)}`;
}
if (c.scope === "session" && c.owner_id) {
const num = c.owner_id.startsWith("conv-") ? c.owner_id.slice(5) : c.owner_id;
return num ? `/chat?c=${encodeURIComponent(num)}` : "/chat";
}
return null;
}
export function SandboxCard() {
const { i18n } = useLiveTranslation();
const isEn = i18n.language.startsWith("en");
const L = (zh: string, en: string) => (isEn ? en : zh);
const [status, setStatus] = React.useState<SandboxGlobalStatus | null>(null);
const [loading, setLoading] = React.useState(false);
const [saving, setSaving] = React.useState(false);
const [pruning, setPruning] = React.useState(false);
const [busyKey, setBusyKey] = React.useState("");
const [image, setImage] = React.useState("");
const [memoryMB, setMemoryMB] = React.useState("2048");
const [cpus, setCpus] = React.useState("2");
const [pidsLimit, setPidsLimit] = React.useState("256");
const [shmSizeMB, setShmSizeMB] = React.useState("512");
const [runtime, setRuntime] = React.useState("");
const [autoStop, setAutoStop] = React.useState(true);
const [idleMin, setIdleMin] = React.useState("20");
const applyStatus = React.useCallback((s: SandboxGlobalStatus) => {
setStatus(s);
setImage(s.image || "");
setMemoryMB(String(s.memory_mb || 2048));
setCpus(String(s.cpus || 2));
setPidsLimit(String(s.pids_limit || 256));
setShmSizeMB(String(s.shm_size_mb || 512));
setRuntime(s.runtime || "");
setAutoStop(s.auto_stop_on_complete !== false);
setIdleMin(String(s.session_idle_minutes || 20));
}, []);
const load = React.useCallback(
async (progressive = false) => {
setLoading(true);
try {
const s = await api.sandboxStatus(!progressive);
applyStatus(s);
if (progressive && s.enabled && s.containers.some((c) => c.state === "running")) {
void api
.sandboxStatus(true)
.then(applyStatus)
.catch(() => {
// ignore transient background stats hydration errors
});
}
} catch {
// keep silent on initial load failure in mock/offline environments
} finally {
setLoading(false);
}
},
[applyStatus],
);
React.useEffect(() => {
void load(true);
}, [load]);
const handleSave = async () => {
setSaving(true);
try {
const updated = await api.updateSandboxSettings({
image: image.trim(),
memory_mb: Number(memoryMB) || 2048,
cpus: Number(cpus) || 2,
pids_limit: Number(pidsLimit) || 256,
shm_size_mb: Number(shmSizeMB) || 512,
runtime: runtime.trim(),
auto_stop_on_complete: autoStop,
session_idle_minutes: Number(idleMin) || 20,
});
applyStatus(updated);
toast.success(L("沙箱配置已保存(新创建或重建的容器生效)", "Sandbox settings saved"));
} catch (e) {
toast.error(e instanceof Error ? e.message : String(e));
} finally {
setSaving(false);
}
};
const handlePrune = async () => {
setPruning(true);
try {
const r = await api.pruneSandboxContainers();
toast.success(L(`已清理 ${r.removed} 个已停止的沙箱容器`, `Removed ${r.removed} stopped sandbox container(s)`));
await load();
} catch (e) {
toast.error(e instanceof Error ? e.message : String(e));
} finally {
setPruning(false);
}
};
const handleStartOne = async (scope: string, ownerID: string) => {
const key = `${scope}:${ownerID}`;
setBusyKey(key);
try {
await api.startSandboxContainer(scope, ownerID);
toast.success(L("容器已启动", "Container started"));
await load();
} catch (e) {
toast.error(e instanceof Error ? e.message : String(e));
} finally {
setBusyKey("");
}
};
const handleStopOne = async (scope: string, ownerID: string) => {
const key = `${scope}:${ownerID}`;
setBusyKey(key);
try {
await api.stopSandboxContainer(scope, ownerID);
toast.success(L("容器已停止", "Container stopped"));
await load();
} catch (e) {
toast.error(e instanceof Error ? e.message : String(e));
} finally {
setBusyKey("");
}
};
const handleRecreateOne = async (c: SandboxContainerInfo) => {
const key = `${c.scope}:${c.owner_id}`;
setBusyKey(key);
try {
await api.recreateSandboxContainer(c.scope, c.owner_id, { pause_task: Boolean(c.task_running) });
toast.success(L("容器已重建(工作区文件已保留)", "Container recreated"));
await load();
} catch (e) {
toast.error(e instanceof Error ? e.message : String(e));
} finally {
setBusyKey("");
}
};
const handleRemoveOne = async (scope: string, ownerID: string) => {
const key = `${scope}:${ownerID}`;
setBusyKey(key);
try {
await api.removeSandboxContainer(scope, ownerID);
toast.success(L("容器已移除", "Container removed"));
await load();
} catch (e) {
toast.error(e instanceof Error ? e.message : String(e));
} finally {
setBusyKey("");
}
};
return (
<Card>
<CardHeader>
<div className="flex flex-wrap items-center justify-between gap-2">
<CardTitle className="flex items-center gap-2 text-base">
<BoxIcon className="size-4" />
{L("沙箱容器隔离", "Sandbox Container Isolation")}
<Badge variant={status?.enabled ? "default" : "secondary"}>
{status?.enabled ? "Docker" : L("本地模式", "Local")}
</Badge>
</CardTitle>
<div className="flex items-center gap-1.5">
<Button size="sm" variant="outline" asChild>
<Link href="/system/sandbox" className="gap-1">
{L("容器管理页", "Manage Containers")}
<ExternalLinkIcon className="size-3.5" />
</Link>
</Button>
{status?.enabled ? (
<Button size="sm" variant="outline" disabled={pruning} onClick={() => void handlePrune()}>
<Trash2Icon className="mr-1 size-3.5" />
{L("清理闲置容器", "Prune Stopped")}
</Button>
) : null}
<Button
size="icon-sm"
variant="ghost"
disabled={loading}
onClick={() => void load()}
title={L("刷新", "Refresh")}
>
<RefreshCwIcon className={`size-4 ${loading ? "animate-spin" : ""}`} />
</Button>
</div>
</div>
<CardDescription>
{status?.enabled
? L(
`已启用 Docker 容器隔离(网络:${status.network},关闭容器间互通)。每个任务和对话在独立非 root 容器内执行命令、脚本与浏览器。`,
`Docker sandbox isolation is active (network: ${status.network}, ICC disabled). Tasks and chat sessions execute tools in isolated non-root containers.`,
)
: L(
"当前为本地执行模式。部署时设置 ARTEX_SANDBOX_MODE=docker 即可启用任务级容器隔离。",
"Running in local mode. Set ARTEX_SANDBOX_MODE=docker on deployment to enable per-task container isolation.",
)}
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
{status?.error ? (
<div className="rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive">
{status.error}
</div>
) : null}
{status?.enabled ? (
<>
<div className="grid grid-cols-1 gap-3 md:grid-cols-3">
<div className="space-y-1">
<Label className="text-xs">{L("沙箱工具镜像", "Sandbox Image")}</Label>
<Input
value={image}
onChange={(e) => setImage(e.target.value)}
placeholder="ruoji6/artex-sandbox:latest"
/>
</div>
<div className="space-y-1">
<Label className="text-xs">{L("单容器内存上限 (MiB)", "Memory Limit (MiB)")}</Label>
<Input type="number" min={256} value={memoryMB} onChange={(e) => setMemoryMB(e.target.value)} />
</div>
<div className="space-y-1">
<Label className="text-xs">{L("单容器 CPU 核数", "CPU Cores")}</Label>
<Input type="number" step="0.5" min={0.25} value={cpus} onChange={(e) => setCpus(e.target.value)} />
</div>
<div className="space-y-1">
<Label className="text-xs">{L("进程数上限 (PIDs)", "PIDs Limit")}</Label>
<Input type="number" min={32} value={pidsLimit} onChange={(e) => setPidsLimit(e.target.value)} />
</div>
<div className="space-y-1">
<Label className="text-xs">{L("共享内存 /dev/shm (MiB)", "Shared Memory (MiB)")}</Label>
<Input type="number" min={64} value={shmSizeMB} onChange={(e) => setShmSizeMB(e.target.value)} />
</div>
<div className="space-y-1">
<Label className="text-xs">
{L("容器运行时(留空默认 runc / 可填 runsc)", "Runtime (blank=runc, or runsc)")}
</Label>
<Input value={runtime} onChange={(e) => setRuntime(e.target.value)} placeholder="runc / runsc" />
</div>
</div>
<div className="flex flex-wrap items-center justify-between gap-3 rounded-md border bg-muted/30 px-3 py-2.5">
<div className="flex items-center gap-3">
<Switch checked={autoStop} onCheckedChange={setAutoStop} />
<div>
<div className="text-xs font-medium">
{L("任务结束或暂停后自动停止容器", "Auto-stop container on task finish or pause")}
</div>
<div className="text-[11px] text-muted-foreground">
{L(
"释放内存与 CPU,工作区文件保留,恢复任务时自动秒级重启。",
"Frees RAM and CPU while keeping workspace files for fast resume.",
)}
</div>
</div>
</div>
<div className="flex items-center gap-2">
<Label className="text-xs text-muted-foreground">
{L("对话空闲停机(分钟)", "Chat idle stop (min)")}
</Label>
<Input
className="h-8 w-20"
type="number"
min={1}
value={idleMin}
onChange={(e) => setIdleMin(e.target.value)}
/>
<Button size="sm" disabled={saving} onClick={() => void handleSave()}>
{saving ? L("保存中…", "Saving…") : L("保存配置", "Save")}
</Button>
</div>
</div>
<div className="space-y-2">
<div className="text-xs font-medium text-muted-foreground">
{L(`当前托管容器 (${status.containers.length})`, `Managed Containers (${status.containers.length})`)}
</div>
{status.containers.length === 0 ? (
<div className="rounded-md border border-dashed px-3 py-4 text-center text-xs text-muted-foreground">
{L(
"暂无沙箱容器(任务或对话执行工具时将自动按需创建)",
"No sandbox containers yet (created on demand when tasks or chats run tools)",
)}
</div>
) : (
<div className="divide-y rounded-md border">
{status.containers.map((c) => {
const key = `${c.scope}:${c.owner_id}`;
const isBusy = busyKey === key;
const href = ownerHref(c);
return (
<div
key={c.container_id || c.name}
className="flex flex-wrap items-center justify-between gap-2 px-3 py-2 text-xs"
>
<div className="min-w-0 flex-1 space-y-0.5">
<div className="flex items-center gap-2">
<Badge variant={c.state === "running" ? "default" : "secondary"}>{c.state}</Badge>
{href ? (
<Link
href={href}
className="inline-flex items-center gap-1 font-mono font-medium hover:underline"
>
{c.scope}:{c.owner_id}
<ExternalLinkIcon className="size-3 text-muted-foreground" />
</Link>
) : (
<span className="font-mono font-medium">
{c.scope}:{c.owner_id}
</span>
)}
<span className="font-mono text-[11px] text-muted-foreground">{c.short_id}</span>
</div>
<div className="truncate font-mono text-[11px] text-muted-foreground">
{c.image} · {c.status_text || c.state}
{c.state === "running"
? ` · CPU ${(c.cpu_percent ?? 0).toFixed(1)}% · MEM ${fmtBytes(c.mem_usage_bytes)}`
: ""}
{` · active=${c.active_runs}`}
</div>
</div>
<div className="flex items-center gap-1">
{c.state === "running" ? (
<Button
size="sm"
variant="outline"
className="h-7 gap-1 text-xs"
disabled={isBusy}
onClick={() => void handleStopOne(c.scope, c.owner_id)}
>
<SquareIcon className="size-3" />
{L("停止", "Stop")}
</Button>
) : (
<Button
size="sm"
variant="default"
className="h-7 gap-1 text-xs"
disabled={isBusy}
onClick={() => void handleStartOne(c.scope, c.owner_id)}
>
<PlayIcon className="size-3" />
{L("启动", "Start")}
</Button>
)}
<Button
size="sm"
variant="outline"
className="h-7 gap-1 text-xs"
disabled={isBusy}
onClick={() => void handleRecreateOne(c)}
>
<RotateCcwIcon className="size-3" />
{L("重建", "Recreate")}
</Button>
<Button
size="icon-sm"
variant="ghost"
className="h-7 w-7 text-destructive"
disabled={isBusy}
onClick={() => void handleRemoveOne(c.scope, c.owner_id)}
title={L("删除容器", "Remove container")}
>
<Trash2Icon className="size-3.5" />
</Button>
</div>
</div>
);
})}
</div>
)}
</div>
</>
) : null}
</CardContent>
</Card>
);
}
+2 -2
View File
@@ -33,8 +33,8 @@ import { useEgressIp } from "../../_components/egress-ip-banner";
import { BackupCard } from "./_components/backup-card";
import { BasicAuthCard } from "./_components/basic-auth-card";
import { McpServerCard } from "./_components/mcp-server-card";
import { SandboxCard } from "./_components/sandbox-card";
import { UpdateCard } from "./_components/update-card";
export default function SystemSettingsPage() {
const { t, liveT, i18n } = useLiveTranslation();
const [credentialAgent, setCredentialAgent] = React.useState(false);
@@ -770,7 +770,7 @@ export default function SystemSettingsPage() {
{isSettingVisible("system", "settings.keywords.backup") ? <BackupCard /> : null}
{isSettingVisible("system", "settings.keywords.basicAuth") ? <BasicAuthCard /> : null}
{isSettingVisible("system", "settings.keywords.mcpServer") ? <McpServerCard /> : null}
{isSettingVisible("system", "settings.keywords.sandbox") ? <SandboxCard /> : null}
<Card
className={`${isSettingVisible("traffic", "settings.keywords.trafficCapture") ? "" : "hidden"} mb-4 break-inside-avoid md:mb-6`}
>
+1
View File
@@ -62,6 +62,7 @@ export const messages = {
"nav.intercept": ["拦截规则", "Interception rules"],
"nav.asset-intercept": ["资产拦截", "Asset interception"],
"nav.approvals": ["审批记录", "Approval history"],
"nav.sandbox": ["沙箱容器", "Sandbox"],
"nav.logs": ["日志", "Logs"],
"nav.settings": ["系统配置", "Settings"],
"search.placeholder": ["搜索页面与功能…", "Search pages and features…"],
+4
View File
@@ -164,6 +164,10 @@ export const settingsMessages = {
"MCP 服务端 访问令牌 token 智能体 编排 外部 bot 审计 白名单 来源 IP",
"mcp server access token agent orchestration external bot audit allowlist whitelist source ip",
],
"settings.keywords.sandbox": [
"沙箱 容器 隔离 docker 镜像 内存 cpu 进程 生命周期 停机 清理",
"sandbox container isolation docker image memory cpu pids lifecycle stop prune",
],
"settings.trafficCapture": ["流量捕获", "Traffic capture"],
"settings.trafficCaptureHelp": [
"开启后,所有 Agent 的 HTTP 流量经记录代理全量落库,并向 Agent 注入 traffic_search / traffic_get 工具与代理配置(提示词含代理说明)。",
+36
View File
@@ -118,6 +118,9 @@ import type {
TrafficResp,
UpdateCheck,
UpdateSettings,
SandboxContainerInfo,
SandboxGlobalStatus,
SandboxRuntimeOverrides,
UsageStats,
WorkspaceFile,
WorkspaceListing,
@@ -1813,4 +1816,37 @@ export const api = {
// 202 即返回,实际下载在后台跑,进度走 /api/update/stream。
applyUpdate: () => post<{ ok: boolean; target: string }>(`/update/apply`),
rollbackUpdate: () => post<{ ok: boolean }>(`/update/rollback`),
// ---- Sandbox container isolation ----
sandboxStatus: (withStats = false) =>
get<SandboxGlobalStatus>(`/sandbox/status${withStats ? "?stats=1" : ""}`),
updateSandboxSettings: (ov: SandboxRuntimeOverrides) => put<SandboxGlobalStatus>("/sandbox/settings", ov),
pruneSandboxContainers: () => post<{ removed: number }>("/sandbox/prune"),
sandboxContainer: (scope: string, ownerID: string, withStats = true) =>
get<SandboxContainerInfo>(
`/sandbox/containers/${encodeURIComponent(scope)}/${encodeURIComponent(ownerID)}${withStats ? "" : "?stats=0"}`,
),
startSandboxContainer: (scope: string, ownerID: string) =>
post<SandboxContainerInfo>(`/sandbox/containers/${encodeURIComponent(scope)}/${encodeURIComponent(ownerID)}/start`),
stopSandboxContainer: (scope: string, ownerID: string) =>
post<SandboxContainerInfo>(`/sandbox/containers/${encodeURIComponent(scope)}/${encodeURIComponent(ownerID)}/stop`),
recreateSandboxContainer: (
scope: string,
ownerID: string,
opts?: { pause_task?: boolean; clear_workspace?: boolean },
) =>
post<SandboxContainerInfo>(
`/sandbox/containers/${encodeURIComponent(scope)}/${encodeURIComponent(ownerID)}/recreate`,
opts ?? {},
),
removeSandboxContainer: (scope: string, ownerID: string) =>
del<{ removed: string }>(`/sandbox/containers/${encodeURIComponent(scope)}/${encodeURIComponent(ownerID)}`),
taskSandbox: (taskID: string, withStats = true) =>
get<SandboxContainerInfo>(`/tasks/${encodeURIComponent(taskID)}/sandbox${withStats ? "" : "?stats=0"}`),
startTaskSandbox: (taskID: string) =>
post<SandboxContainerInfo>(`/tasks/${encodeURIComponent(taskID)}/sandbox/start`),
stopTaskSandbox: (taskID: string, pauseTask = false) =>
post<SandboxContainerInfo>(`/tasks/${encodeURIComponent(taskID)}/sandbox/stop`, { pause_task: pauseTask }),
recreateTaskSandbox: (taskID: string, opts?: { pause_task?: boolean; clear_workspace?: boolean }) =>
post<SandboxContainerInfo>(`/tasks/${encodeURIComponent(taskID)}/sandbox/recreate`, opts ?? {}),
};
+53
View File
@@ -2004,3 +2004,56 @@ export interface TaskFileListing {
truncated: boolean;
missing: boolean;
}
// ---- Sandbox Container Isolation ----
export interface SandboxContainerInfo {
scope: "task" | "session" | "ephemeral" | string;
owner_id: string;
owner_title?: string;
task_running?: boolean;
name: string;
container_id?: string;
short_id?: string;
image: string;
state: "running" | "exited" | "created" | "missing" | "local" | "error" | string;
status_text?: string;
created_at?: string;
started_at?: string;
active_runs: number;
cpu_percent?: number;
mem_usage_bytes?: number;
mem_limit_bytes?: number;
pids_current?: number;
work_dir_container: string;
network?: string;
runtime?: string;
error?: string;
}
export interface SandboxGlobalStatus {
mode: "local" | "docker" | string;
enabled: boolean;
available: boolean;
error?: string;
image: string;
network: string;
runtime: string;
memory_mb: number;
cpus: number;
pids_limit: number;
shm_size_mb: number;
auto_stop_on_complete: boolean;
session_idle_minutes: number;
containers: SandboxContainerInfo[];
}
export interface SandboxRuntimeOverrides {
image?: string;
memory_mb?: number;
cpus?: number;
pids_limit?: number;
shm_size_mb?: number;
runtime?: string;
auto_stop_on_complete?: boolean;
session_idle_minutes?: number;
}
@@ -3,6 +3,7 @@ import {
Ban,
BellRing,
Bot,
Box,
Brain,
Bug,
CalendarClock,
@@ -95,6 +96,7 @@ export const sidebarItems: NavGroup[] = [
{ id: "intercept", title: "拦截规则", url: "/system/intercept", icon: ShieldAlert },
{ id: "asset-intercept", title: "资产拦截", url: "/system/intercept/assets", icon: Ban },
{ id: "approvals", title: "审批记录", url: "/system/intercept/approvals", icon: ClipboardList },
{ id: "sandbox", title: "沙箱容器", url: "/system/sandbox", icon: Box },
{ id: "logs", title: "日志", url: "/system/logs", icon: ScrollText },
{ id: "settings", title: "系统配置", url: "/system/settings", icon: Settings2 },
],