mirror of
https://github.com/RuoJi6/ARTEX.git
synced 2026-12-02 20:01:51 +08:00
- 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
206 lines
6.6 KiB
Go
206 lines
6.6 KiB
Go
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
|
||
})
|
||
}
|