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

+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 {