mirror of
https://github.com/RuoJi6/ARTEX.git
synced 2026-11-29 02:51:51 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ea4377ef9a |
No files matched your search
@@ -17,3 +17,15 @@ ARTEX_LLM_PROXY=
|
||||
|
||||
# HTTP User-Agent;留空时从浏览器 UA 样本中随机抽选,填写则使用固定值
|
||||
ARTEX_HTTP_USER_AGENT=
|
||||
|
||||
# 容器与工具执行资源上限(防止单个子进程吃满宿主机内存导致 swap 抖动)
|
||||
# ARTEX_MEMORY_LIMIT 同时用于 Docker mem_limit 与 memswap_limit(默认 4g,禁止容器使用宿主机 swap)
|
||||
# 小内存 VPS(如 4G/8G)建议按宿主机可用内存的一半左右设置,为系统和 PostgreSQL 留出余量
|
||||
ARTEX_MEMORY_LIMIT=4g
|
||||
ARTEX_PIDS_LIMIT=512
|
||||
# 单条 Bash / 自定义命令或脚本工具的内存上限(MiB,默认 2048;设为 0 关闭)
|
||||
ARTEX_TOOL_MEMORY_LIMIT_MB=2048
|
||||
# Bash 和自定义命令/脚本的默认超时时间(秒,默认 120)
|
||||
ARTEX_TOOL_TIMEOUT_S=120
|
||||
# 单条命令的进程/线程数上限(仅在 Linux cgroup v2 可委托时生效,默认 256;设为 0 关闭)
|
||||
ARTEX_TOOL_PIDS_LIMIT=256
|
||||
@@ -145,6 +145,13 @@ docker compose up -d # 拉取 ruoji6/artex 镜像 + postgres
|
||||
|
||||
`.env` 中默认 `ARTEX_IMAGE=ruoji6/artex`,`ARTEX_TAG=latest` 使用最新镜像,也可固定为 `v0.3.17`(完整镜像地址 `ruoji6/artex:v0.3.17`)。镜像支持 `linux/amd64` 和 `linux/arm64`,Docker 会自动选择与宿主机匹配的架构,ARM64 Kali 无需自行编译。初次部署请修改 `POSTGRES_PASSWORD`;运行服务无需配置 Docker Hub 发布 Token。
|
||||
|
||||
#### 内存与进程保护
|
||||
|
||||
- **Compose 容器**:`artex` 默认最多使用 **4 GiB 内存、512 个进程/线程**,并禁用容器 swap;PostgreSQL 不受这两个上限限制。通过 `.env` 的 `ARTEX_MEMORY_LIMIT`、`ARTEX_PIDS_LIMIT` 调整。小内存 VPS 应调低内存上限,给宿主机、数据库和其他服务留出余量。更新 Compose 或 `.env` 后,运行 `docker compose up -d artex` 重建容器;只热更新程序不会改变容器限制。
|
||||
- **单条工具命令**:前台/后台 Bash 和自定义命令、Python 脚本默认使用 **2048 MiB** 内存和 **120 秒**超时。显式 `timeout_ms` 最多为 600 秒(如果运营者将默认值调得更长,则以该默认值为上限)。用 `ARTEX_TOOL_MEMORY_LIMIT_MB`、`ARTEX_TOOL_TIMEOUT_S` 调整;内存上限设为 `0` 时关闭单命令内存保护。超时的前台命令会被终止,不再自动转入后台。内存超限会返回明确错误;显式后台任务可用 `TaskOutput` 查看原因。
|
||||
- **执行方式**:可委托的 Linux cgroup v2 使用内核内存上限,启用 PID 控制器时还应用 `ARTEX_TOOL_PIDS_LIMIT`(默认 256,`0` 表示关闭)。默认只在服务自身 cgroup 内创建子组;本地部署可通过 `ARTEX_TOOL_CGROUP_PARENT` 指定由管理员委托且包含服务的父组,容器/服务限制应设在该组或其上层。普通 Docker 中 cgroup 往往不可写,无需加特权:Linux 使用进程树 RSS 加换出内存采样兜底,macOS 使用 RSS 采样。采样不是硬上限,某些尖峰可能只被容器限制挡住;Windows 不支持单命令内存采样。SDK 的 `Monitor` 和交互式 PTY 不应用单命令限制,在 Compose 中仍受容器限制。
|
||||
- **查看配置**:启动日志和登录后的 `GET /api/system/metrics` 的 `limits` 字段显示工具限制与执行方式;Linux 对可识别的容器 cgroup 同时报告内存和 PID 上限。
|
||||
|
||||
远程 MCP 可在系统设置中选择 `http`(Streamable HTTP)或 `sse`(旧版 SSE)。
|
||||
旧版 SSE 服务通常使用 `GET /sse` 建立事件流,再通过服务返回的
|
||||
`/message?sessionId=...` 接收 JSON-RPC 请求;配置时将 URL 填为 `/sse`,请求头按
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"log"
|
||||
"runtime/debug"
|
||||
|
||||
"github.com/Autumn-27/artex/internal/toolguard"
|
||||
actool "github.com/Autumn-27/norma/tool"
|
||||
)
|
||||
|
||||
@@ -79,6 +80,17 @@ func AugmentTools(ctx context.Context, agentKey string, base []actool.CoreTool)
|
||||
return out, def, cleanup
|
||||
}
|
||||
|
||||
// Install the guarded handler before ToolResolve decorates it with DB defaults.
|
||||
func guardedDefaultTools() []actool.CoreTool {
|
||||
tools := actool.DefaultTools()
|
||||
for i, t := range tools {
|
||||
if t.Name() == "Bash" {
|
||||
tools[i] = toolguard.NewBash()
|
||||
}
|
||||
}
|
||||
return tools
|
||||
}
|
||||
|
||||
// guardPanic turns a panicking tool handler into an ordinary tool error. The
|
||||
// harness runs each tool on its own goroutine, so a panic inside a handler can't
|
||||
// be recovered by the caller that started the run — it takes the whole process
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGuardedBashPreservesDecoratedDefaults(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("POSIX shell syntax")
|
||||
}
|
||||
for _, tool := range guardedDefaultTools() {
|
||||
if tool.Name() != "Bash" {
|
||||
continue
|
||||
}
|
||||
decorated := DecorateTool(tool, "custom description", map[string]any{
|
||||
"properties": map[string]any{"timeout_ms": map[string]any{"type": "integer", "default": 50}},
|
||||
})
|
||||
res, err := decorated.Call(context.Background(), []byte(`{"command":"sleep 2"}`), nil)
|
||||
if err != nil || !res.IsError || !strings.Contains(res.Flatten(), "timed out") {
|
||||
t.Fatalf("expected timeout injected by tool decorator, got %s %v", res.Flatten(), err)
|
||||
}
|
||||
return
|
||||
}
|
||||
t.Fatal("Bash not found")
|
||||
}
|
||||
+1
-1
@@ -120,7 +120,7 @@ func (c *ChatAgent) Chat(ctx context.Context, agentKey, sessionID, message strin
|
||||
// Pure assistant: DefaultTools as the base; AugmentTools layers in the key's
|
||||
// visible skills/MCP and lets the DB tools table filter/override. DefaultTools
|
||||
// have no tools-table rows, so they always pass through.
|
||||
base := actool.DefaultTools()
|
||||
base := guardedDefaultTools()
|
||||
ctx = WithRunInfo(ctx, RunInfo{SessionID: sessionID})
|
||||
tools, def, cleanup := AugmentTools(ctx, agentKey, base)
|
||||
defer cleanup()
|
||||
|
||||
+1
-2
@@ -95,7 +95,6 @@ const mainAgentDefaultTmpl = `你是一个授权渗透测试系统的"主 agent"
|
||||
**当任务目标已全部达成时**(graph_overview 里 goals 均为 met):下发前先判断这条意图背后是否隐含一个"新的、要达成的结果"。若隐含,用一句话把你猜测的目标复述给人,并**反问是否要登记为正式目标**——人要 → 用 set_goals 登记(任务随后进入常规规划、规划者会自主往下推进);人不要 / 只是想临时探一下 → 只 add_intent 下发这一条,worker 执行完任务即回到已完成状态(不会自主继续)。若这条意图明显只是一次性查证、不隐含新目标,直接 add_intent 即可,不必每次都问。
|
||||
- 人想"对某条正在运行的意图(work)实时纠偏(别再走 X、聚焦 Y)" → 用 steer_work(不打断、不丢已有进展,worker 下一步动作前生效);先用 get_worker_output 看它在干嘛。方向整个错了则改用 add_intent 另下新意图。
|
||||
- 人想"新增一个要达成的最终目标" → 用 set_goals 增补目标。系统会把该目标写入任务图并**自动把已完成/暂停的任务拉回运行态继续跑**(规划者随后会据此重新判断是否达成),无需人工再点恢复。
|
||||
- 人想"恢复已暂停的任务,或重新打开已结束但仍有未完成目标/待执行(open)意图的任务" → 用 resume_task 原地将当前任务拉回运行态继续跑(保留已有探索图、发现与 frontier),不必新建重复任务。
|
||||
- 人想"增/改测试约束(允许/禁止某类操作,如『仅测当前端口』『禁止爆破』『只做被动侦察』)" → 用 set_constraints 登记(type=allow 允许 / type=deny 禁止)。约束会在下一轮规划时注入 planner/worker 的提示词以框定探索边界;也可在总览「约束管理」里增删改。
|
||||
3. 用人话简洁回复,说明你做了什么。
|
||||
|
||||
@@ -127,7 +126,7 @@ func (m *MainAgent) Chat(ctx context.Context, taskID int64, mainSeg int, as *db.
|
||||
tsx.steerWork = m.steerWork // enable steer_work tool (nil = unavailable)
|
||||
// 领域工具 + 基础默认工具集(Read/Write/Edit/MultiEdit/LS/Glob/Grep/Bash)
|
||||
// 资产覆盖度功能关闭时剔除 add_task_scope/list_untested_assets(不入 prompt)。
|
||||
base := append(tsx.DropCoverageTools(tsx.MainAgentTools()), actool.DefaultTools()...)
|
||||
base := append(tsx.DropCoverageTools(tsx.MainAgentTools()), guardedDefaultTools()...)
|
||||
ctx = WithRunInfo(ctx, RunInfo{TaskID: taskID, ExplorationID: explorationID(ts)})
|
||||
tools, def, cleanup := AugmentTools(ctx, "mainagent", base)
|
||||
defer cleanup()
|
||||
|
||||
+1
-1
@@ -374,7 +374,7 @@ func (p *Planner) Plan(ctx context.Context, taskID int64, as *db.AssetStore, ts
|
||||
}
|
||||
// 领域工具 + 基础默认工具集(Read/Write/Edit/MultiEdit/LS/Glob/Grep/Bash)
|
||||
// 资产覆盖度功能关闭时剔除 add_task_scope/list_untested_assets(不入 prompt)。
|
||||
base := append(tsx.DropCoverageTools(tsx.PlannerTools()), actool.DefaultTools()...)
|
||||
base := append(tsx.DropCoverageTools(tsx.PlannerTools()), guardedDefaultTools()...)
|
||||
ctx = WithRunInfo(ctx, RunInfo{TaskID: taskID, ExplorationID: explorationID(ts)})
|
||||
tools, def, cleanup := AugmentTools(ctx, "planner", base)
|
||||
defer cleanup()
|
||||
|
||||
@@ -15,12 +15,11 @@ package agent
|
||||
const autoDefaultTmpl = `你是 **Auto**,这个渗透测试平台的「操作助手」。你不亲自渗透,而是**用工具操作平台**、按用户指令把事情办好。
|
||||
|
||||
你能做的(取决于给你开放了哪些工具):
|
||||
1. **任务操作**:list_tasks 看全局、spawn_task 起子任务、get_task_graph / list_task_findings 读某任务的进展与漏洞、get_task_worker_trace 看某个 work 的执行过程、pause_task 暂停、resume_task 恢复暂停任务或原地重新打开已结束且仍有未完成目标/待执行意图的任务、add_task_hint 给任务注入提示、set_task_goals 给任务增补最终目标(自动拉回运行态)、add_task_intent 给任务直投高优先级探索意图(自动拉回运行态)。
|
||||
1. **任务操作**:list_tasks 看全局、spawn_task 起子任务、get_task_graph / list_task_findings 读某任务的进展与漏洞、get_task_worker_trace 看某个 work 的执行过程、pause_task 暂停、add_task_hint 给任务注入提示。
|
||||
2. **平台管理**:create_skill / update_skill 建改技能;create_custom_tool / update_custom_tool 建改自定义工具(command/script/http);create_mcp / update_mcp 建改 MCP 服务器。
|
||||
|
||||
原则:
|
||||
- 先看清现状(list_tasks / get_task_graph 等)再动手;一步到位、少空转。
|
||||
- **原地继续优先于新建任务**:当用户要求继续、重开或补充已暂停/已结束的已有任务时,优先在原任务上操作(仍有 open 目标或 open 意图 → 用 resume_task 原地恢复;需要新增最终目标 → 用 set_task_goals;需要立刻测具体方向 → 用 add_task_intent),保留已有探索图与发现,不要用 spawn_task 新建重复任务。
|
||||
- 涉及漏洞资产或拓扑时,优先使用用户引用快照中的 asset_topology.zone/zone_reason;三层区域含义固定为 internet(互联网入口)、boundary(公开暴露服务/应用/端点)、internal(私有地址及其业务资产)。不要仅凭 kind 改写区域,也不要把没有真实关系证据的跨区连接说成已验证通路。
|
||||
- 建/改 skill、工具、MCP 时,把用户意图翻译成正确的结构化参数(kind/exec/schema 等),字段拿不准就按最小可用填。
|
||||
- 用人话简洁汇报你做了什么、结果如何;只根据工具真实返回作答,不臆造。
|
||||
|
||||
+9
-6
@@ -25,6 +25,7 @@ import (
|
||||
"github.com/Autumn-27/norma/compaction"
|
||||
"github.com/Autumn-27/norma/llm"
|
||||
acperm "github.com/Autumn-27/norma/permission"
|
||||
actool "github.com/Autumn-27/norma/tool"
|
||||
"github.com/Autumn-27/norma/transcript"
|
||||
)
|
||||
|
||||
@@ -519,12 +520,14 @@ func TestConnection(ctx context.Context, c Config) (time.Duration, string, error
|
||||
// "已中断/length/resume" 一团糟。给足预算让它把 OK 干净吐完(finish=stop)。
|
||||
// EscalateMaxTokens 保持 false:不因截断而抬额重试,避免 resume 循环空烧。
|
||||
reply, err := agentcore.Run(ctx, agentcore.Options{
|
||||
Provider: prov,
|
||||
SystemPrompt: []string{"你是连接测试。直接输出两个字符 OK 即可,不要思考、不要解释、不要别的。"},
|
||||
PermissionMode: acperm.ModeBypass,
|
||||
MaxTurns: 1,
|
||||
MaxTokens: 8192,
|
||||
NonStreaming: !c.Stream, // 用该 profile 的真实收发模式做连接测试
|
||||
Provider: prov,
|
||||
Tools: []actool.CoreTool{},
|
||||
DisableBackgroundTasks: true,
|
||||
SystemPrompt: []string{"你是连接测试。直接输出两个字符 OK 即可,不要思考、不要解释、不要别的。"},
|
||||
PermissionMode: acperm.ModeBypass,
|
||||
MaxTurns: 1,
|
||||
MaxTokens: 8192,
|
||||
NonStreaming: !c.Stream, // 用该 profile 的真实收发模式做连接测试
|
||||
}, "ping")
|
||||
lat := time.Since(start)
|
||||
if err != nil {
|
||||
|
||||
@@ -221,8 +221,6 @@ func (t *ToolSet) ListWorkerTracesTool() actool.CoreTool { return t.listWorker
|
||||
func (t *ToolSet) SearchWorkerTracesTool() actool.CoreTool { return t.searchAllWorkerTraces() }
|
||||
func (t *ToolSet) NodeDetailTool() actool.CoreTool { return t.nodeDetail() }
|
||||
func (t *ToolSet) AddHintTool() actool.CoreTool { return t.addHint() }
|
||||
func (t *ToolSet) AddIntentTool() actool.CoreTool { return t.addIntent() }
|
||||
func (t *ToolSet) SetGoalsTool() actool.CoreTool { return t.setGoals() }
|
||||
|
||||
// SetEnrich wires the async enrichment engine (DNS/HTTP auto-completion).
|
||||
func (t *ToolSet) SetEnrich(e EnrichTrigger) { t.enrich = e }
|
||||
|
||||
+8
-5
@@ -6,14 +6,17 @@ import (
|
||||
actool "github.com/Autumn-27/norma/tool"
|
||||
)
|
||||
|
||||
// newAgentSession installs the configurable WebFetch before the SDK builds the
|
||||
// registry, so every agent role gets one tool and the same proxy/TLS settings.
|
||||
// newAgentSession installs ARTEX's resource-guarded Bash tool and configurable
|
||||
// WebFetch before the SDK builds the registry, so every agent role gets the
|
||||
// same memory/timeout guards and proxy/TLS settings.
|
||||
func newAgentSession(opts agentcore.Options) *agentcore.Session {
|
||||
if opts.Tools == nil {
|
||||
opts.Tools = guardedDefaultTools()
|
||||
} else if opts.EnableWebFetch {
|
||||
opts.Tools = append([]actool.CoreTool{}, opts.Tools...)
|
||||
}
|
||||
if opts.EnableWebFetch {
|
||||
opts.EnableWebFetch = false
|
||||
if opts.Tools == nil {
|
||||
opts.Tools = actool.DefaultTools()
|
||||
}
|
||||
opts.Tools = append(opts.Tools, webfetch.New(actool.WebFetchConfig{
|
||||
Proxy: opts.WebFetchProxy,
|
||||
CACert: opts.WebFetchCACert,
|
||||
|
||||
+2
-2
@@ -148,14 +148,14 @@ func NewWorker(prov llm.Provider, model, workDir string, tx *transcript.Store, w
|
||||
return &Worker{prov: prov, model: model, workDir: workDir, tx: tx, window: window, maxTurns: maxTurns, extraTools: extra}
|
||||
}
|
||||
|
||||
// defaultToolsExcept returns actool.DefaultTools() minus the named tools (by
|
||||
// defaultToolsExcept returns guardedDefaultTools() minus the named tools (by
|
||||
// CoreTool.Name()). Used to trim SDK default tools an agent shouldn't have.
|
||||
func defaultToolsExcept(exclude ...string) []actool.CoreTool {
|
||||
drop := make(map[string]bool, len(exclude))
|
||||
for _, n := range exclude {
|
||||
drop[n] = true
|
||||
}
|
||||
all := actool.DefaultTools()
|
||||
all := guardedDefaultTools()
|
||||
out := make([]actool.CoreTool, 0, len(all))
|
||||
for _, t := range all {
|
||||
if !drop[t.Name()] {
|
||||
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
|
||||
"github.com/Autumn-27/artex/agent"
|
||||
"github.com/Autumn-27/artex/config"
|
||||
"github.com/Autumn-27/artex/internal/toolguard"
|
||||
"github.com/Autumn-27/artex/selfupdate"
|
||||
"github.com/Autumn-27/artex/server"
|
||||
)
|
||||
@@ -47,6 +48,9 @@ func printBanner(addr string) {
|
||||
// whether to relaunch us (see selfupdate.ExitRestart) — so the body has to live
|
||||
// in a function that can *return* rather than os.Exit past its own defers.
|
||||
func main() {
|
||||
if code, handled := toolguard.BackgroundHelper(os.Args[1:]); handled {
|
||||
os.Exit(code)
|
||||
}
|
||||
os.Exit(run())
|
||||
}
|
||||
|
||||
@@ -120,6 +124,7 @@ func run() int {
|
||||
defer settle.Stop()
|
||||
|
||||
log.Printf("[config] skill 目录: %s", skillDir)
|
||||
log.Printf("[config] 工具资源限制: %s", toolguard.FromEnv().Summary())
|
||||
srv := server.New(ctx, mgr, skillDir, *dataDir, config.BaseDir())
|
||||
defer srv.Close()
|
||||
httpSrv := &http.Server{
|
||||
|
||||
@@ -29,6 +29,9 @@ services:
|
||||
ARTEX_LLM_BASE_URL: ${ARTEX_LLM_BASE_URL:-}
|
||||
ARTEX_LLM_PROXY: ${ARTEX_LLM_PROXY:-}
|
||||
ARTEX_HTTP_USER_AGENT: ${ARTEX_HTTP_USER_AGENT:-}
|
||||
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:-}
|
||||
ports:
|
||||
- "8787:8787"
|
||||
- "127.0.0.1:8788:8788"
|
||||
@@ -39,6 +42,11 @@ 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}
|
||||
pids_limit: ${ARTEX_PIDS_LIMIT:-512}
|
||||
restart: unless-stopped
|
||||
|
||||
volumes:
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
package toolguard
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
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]"
|
||||
)
|
||||
|
||||
// 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.
|
||||
func runGuardedBashBackground(tc *actool.ToolContext, 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
|
||||
}
|
||||
var dir string
|
||||
scope := newCgroupScope(cfg.MemoryLimitBytes(), cfg.PidsLimit)
|
||||
if scope != nil {
|
||||
dir = scope.dir
|
||||
scope.CloseFD()
|
||||
}
|
||||
env := append([]string{}, tc.Env...)
|
||||
// Pass the command as data, not shell syntax in the trampoline.
|
||||
env = append(env, backgroundExe+"="+exe, backgroundCommand+"="+command,
|
||||
backgroundTimeout+"="+timeout.String(), backgroundCgroup+"="+dir,
|
||||
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] + "..."
|
||||
}
|
||||
mgr := tc.Tasks
|
||||
t, err := mgr.Spawn(actool.SpawnSpec{
|
||||
Command: trampoline, Kind: actool.KindBash, WorkingDir: tc.WorkingDir,
|
||||
Description: desc, Env: env,
|
||||
})
|
||||
if err != nil {
|
||||
if scope != nil {
|
||||
scope.Cleanup()
|
||||
}
|
||||
return actool.Errorf("Error: failed to start background command: " + err.Error()), nil
|
||||
}
|
||||
mgr.Background(t.ID)
|
||||
if scope != nil {
|
||||
go func(id string) {
|
||||
// The helper might be SIGKILLed by TaskStop; its parent therefore
|
||||
// owns the scope and cleans it up after the task exits.
|
||||
_, done := mgr.Wait(context.Background(), id, timeout)
|
||||
if !done {
|
||||
_, done = mgr.Wait(context.Background(), id, 5*time.Second)
|
||||
}
|
||||
if !done {
|
||||
mgr.Kill(id)
|
||||
}
|
||||
scope.Cleanup()
|
||||
}(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
|
||||
}
|
||||
|
||||
// BackgroundHelper handles the internal helper invocation before normal app
|
||||
// startup. The helper uses the task manager's cwd, environment, and output file.
|
||||
func BackgroundHelper(args []string) (exitCode int, handled bool) {
|
||||
if len(args) != 1 || args[0] != backgroundArg {
|
||||
return 0, false
|
||||
}
|
||||
command, dir := os.Getenv(backgroundCommand), os.Getenv(backgroundCgroup)
|
||||
timeout, err := time.ParseDuration(os.Getenv(backgroundTimeout))
|
||||
for _, name := range []string{backgroundExe, backgroundCommand, backgroundTimeout, backgroundCgroup} {
|
||||
_ = os.Unsetenv(name)
|
||||
}
|
||||
if command == "" || err != nil || timeout <= 0 {
|
||||
fmt.Fprintln(os.Stderr, "invalid background tool invocation")
|
||||
return 1, true
|
||||
}
|
||||
cfg := FromEnv()
|
||||
cfg.MaxOutputBytes -= 4096 // leave room for the error note below norma's task-file cap
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
shell, flags := platformShellCmd()
|
||||
cmd := exec.Command(shell, append(flags, command)...)
|
||||
group := os.Getpid()
|
||||
if runtime.GOOS == "windows" {
|
||||
group = 0 // Windows terminates the process tree by PID, without a Unix group.
|
||||
}
|
||||
res := run(ctx, cfg, cmd, openCgroupScope(dir), group, os.Stdout)
|
||||
if res.OutputTruncated {
|
||||
fmt.Fprintln(os.Stderr, outputLimitNote)
|
||||
}
|
||||
switch {
|
||||
case res.MemoryKilled:
|
||||
fmt.Fprintln(os.Stderr, FormatMemoryKilled(res.PeakMemoryBytes, res.MemoryLimitBytes, res.KilledByCgroup))
|
||||
return 1, true
|
||||
case res.TimedOut:
|
||||
fmt.Fprintln(os.Stderr, timeoutNote(timeout))
|
||||
return 1, true
|
||||
case res.ExitCode >= 0:
|
||||
return res.ExitCode, true
|
||||
default:
|
||||
fmt.Fprintf(os.Stderr, "[failed to run: %v]\n", res.Err)
|
||||
return 1, true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package toolguard
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"maps"
|
||||
"os"
|
||||
"os/exec"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Autumn-27/norma/permission"
|
||||
actool "github.com/Autumn-27/norma/tool"
|
||||
)
|
||||
|
||||
// NewBash keeps the SDK permission floor but runs commands through ARTEX's guard.
|
||||
func NewBash() actool.CoreTool {
|
||||
base := actool.NewBash()
|
||||
schema := maps.Clone(base.InputSchema())
|
||||
props := maps.Clone(schema["properties"].(map[string]any))
|
||||
if _, ok := props["run_in_background"]; ok {
|
||||
props["run_in_background"] = map[string]any{"type": "boolean", "description": "Run asynchronously; read output with TaskOutput and stop it with TaskStop. The same memory and time limits apply."}
|
||||
}
|
||||
props["timeout_ms"] = map[string]any{"type": "integer", "description": "Command timeout in milliseconds (operator-configured default, normally 120000)."}
|
||||
schema["properties"] = props
|
||||
return actool.Build(actool.Spec{
|
||||
Name: base.Name(),
|
||||
Description: base.Description(),
|
||||
Prompt: strings.Replace(base.Prompt(), "A timeout (default 120s, max 600s) applies.", "Commands are terminated at their timeout instead of moving to the background.", 1),
|
||||
Schema: schema,
|
||||
ReadOnly: base.IsReadOnly,
|
||||
Concurrent: base.IsConcurrencySafe,
|
||||
Permissions: base.CheckPermissions,
|
||||
Run: runGuardedBash,
|
||||
})
|
||||
}
|
||||
|
||||
func runGuardedBash(ctx context.Context, input json.RawMessage, tc *actool.ToolContext) (actool.Result, error) {
|
||||
var in struct {
|
||||
Command string `json:"command"`
|
||||
TimeoutMS int `json:"timeout_ms"`
|
||||
RunInBackground bool `json:"run_in_background"`
|
||||
}
|
||||
if err := json.Unmarshal(input, &in); err != nil {
|
||||
return actool.Result{}, err
|
||||
}
|
||||
if strings.TrimSpace(in.Command) == "" {
|
||||
return actool.Errorf("Error: command is required"), nil
|
||||
}
|
||||
|
||||
// Custom command tools can invoke this handler directly, outside norma's
|
||||
// permission pipeline. Always enforce the same catastrophic-command floor.
|
||||
if dec := actool.NewBash().CheckPermissions(ctx, input, permission.Context{}); dec.Behavior == permission.Deny {
|
||||
return actool.Errorf(dec.Message), nil
|
||||
}
|
||||
cfg := FromEnv()
|
||||
timeout := cfg.ResolveTimeout(in.TimeoutMS)
|
||||
if in.RunInBackground && tc != nil && tc.Tasks != nil && !actool.BackgroundTasksDisabled() {
|
||||
return runGuardedBashBackground(tc, cfg, in.Command, timeout)
|
||||
}
|
||||
|
||||
cctx, cancel := context.WithTimeout(ctx, timeout)
|
||||
defer cancel()
|
||||
|
||||
shell, flags := platformShellCmd()
|
||||
cmd := exec.Command(shell, append(flags, in.Command)...)
|
||||
if tc != nil {
|
||||
cmd.Dir = tc.WorkingDir
|
||||
if env := mergedEnv(tc.Env); env != nil {
|
||||
cmd.Env = env
|
||||
}
|
||||
}
|
||||
|
||||
res := Run(cctx, cfg, cmd)
|
||||
out := actool.Capture(tc, res.Output)
|
||||
if res.OutputTruncated {
|
||||
out += outputLimitNote
|
||||
}
|
||||
if res.MemoryKilled {
|
||||
if strings.TrimSpace(out) == "" {
|
||||
out = "(no output)"
|
||||
}
|
||||
return actool.Errorf(out + "\n\n" + FormatMemoryKilled(res.PeakMemoryBytes, res.MemoryLimitBytes, res.KilledByCgroup)), nil
|
||||
}
|
||||
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: %v]", out, res.Err)), nil
|
||||
}
|
||||
if strings.TrimSpace(out) == "" {
|
||||
out = "(command produced no output)"
|
||||
}
|
||||
return actool.Text(out), nil
|
||||
}
|
||||
|
||||
func platformShellCmd() (string, []string) {
|
||||
if runtime.GOOS == "windows" {
|
||||
return "powershell", []string{"-NoProfile", "-NonInteractive", "-Command"}
|
||||
}
|
||||
return "bash", []string{"-c"}
|
||||
}
|
||||
|
||||
func mergedEnv(extra []string) []string {
|
||||
if len(extra) == 0 {
|
||||
return nil
|
||||
}
|
||||
return append(os.Environ(), extra...)
|
||||
}
|
||||
|
||||
func timeoutNote(limit time.Duration) string {
|
||||
return fmt.Sprintf("\n\n[command timed out (configured limit %s)]", limit)
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package toolguard
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
actool "github.com/Autumn-27/norma/tool"
|
||||
)
|
||||
|
||||
func TestBashForeground(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("POSIX shell syntax")
|
||||
}
|
||||
tc := &actool.ToolContext{WorkingDir: t.TempDir(), Env: []string{"ARTEX_TEST_MARKER=from-session"}}
|
||||
res, _ := NewBash().Call(context.Background(), []byte(`{"command":"printf '%s %s' \"$ARTEX_TEST_MARKER\" \"$PWD\""}`), tc)
|
||||
cwd, err := filepath.EvalSymlinks(tc.WorkingDir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if res.IsError || res.Flatten() != "from-session "+cwd {
|
||||
t.Fatalf("cwd/env not passed: %s", res.Flatten())
|
||||
}
|
||||
res, _ = NewBash().Call(context.Background(), []byte(`{"command":"sleep 10", "timeout_ms":100}`), tc)
|
||||
if !res.IsError || !strings.Contains(res.Flatten(), "timed out") {
|
||||
t.Fatalf("missing timeout: %s", res.Flatten())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBashBackground(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("POSIX shell syntax")
|
||||
}
|
||||
t.Setenv("AGENT_CORE_DISABLE_BACKGROUND_TASKS", "")
|
||||
t.Setenv(EnvToolMemoryLimitMB, "0")
|
||||
t.Setenv(EnvToolPidsLimit, "0")
|
||||
mgr, err := actool.NewManager("artex-toolguard-" + filepath.Base(filepath.Dir(t.TempDir())))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(mgr.Cleanup)
|
||||
tc := &actool.ToolContext{Tasks: mgr, WorkingDir: t.TempDir(), Env: []string{"ARTEX_TEST_MARKER=background-session"}}
|
||||
invoke := func(command string, timeoutMS int) string {
|
||||
t.Helper()
|
||||
in, _ := json.Marshal(map[string]any{"command": command, "run_in_background": true, "timeout_ms": timeoutMS})
|
||||
res, err := NewBash().Call(context.Background(), in, tc)
|
||||
if err != nil || res.IsError {
|
||||
t.Fatalf("start background command: %s %v", res.Flatten(), err)
|
||||
}
|
||||
tasks := mgr.List()
|
||||
return tasks[len(tasks)-1].ID
|
||||
}
|
||||
id := invoke(`printf '%s\n' "$ARTEX_TEST_MARKER"; sleep 10`, 500)
|
||||
info, done := mgr.Wait(context.Background(), id, 5*time.Second)
|
||||
out, err := mgr.Output(id, 1024)
|
||||
if !done || info.Status != actool.TaskFailed || err != nil || !strings.Contains(out, "background-session") || !strings.Contains(out, "timed out") {
|
||||
t.Fatalf("background timeout not surfaced: %+v, output %q, error %v", info, out, err)
|
||||
}
|
||||
|
||||
id = invoke(`touch ready; sleep 2; touch survived`, 5000)
|
||||
waitUntil := time.Now().Add(3 * time.Second)
|
||||
for {
|
||||
if _, err := os.Stat(filepath.Join(tc.WorkingDir, "ready")); err == nil {
|
||||
break
|
||||
}
|
||||
if time.Now().After(waitUntil) {
|
||||
t.Fatal("background command did not start")
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
mgr.Kill(id)
|
||||
if info, done := mgr.Wait(context.Background(), id, 5*time.Second); !done || info.Status != actool.TaskKilled {
|
||||
t.Fatalf("TaskStop did not stop helper: %+v", info)
|
||||
}
|
||||
// A stopped shell would otherwise write this file after its sleep.
|
||||
time.Sleep(2200 * time.Millisecond)
|
||||
if _, err := os.Stat(filepath.Join(tc.WorkingDir, "survived")); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("TaskStop left the inner shell running: stat = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBashBackgroundMemory(t *testing.T) {
|
||||
if !watchdogAvailable() {
|
||||
t.Skip("requires a process memory watchdog")
|
||||
}
|
||||
t.Setenv("AGENT_CORE_DISABLE_BACKGROUND_TASKS", "")
|
||||
t.Setenv(EnvToolMemoryLimitMB, "16")
|
||||
t.Setenv(EnvToolPidsLimit, "0")
|
||||
mgr, err := actool.NewManager("artex-toolguard-memory-" + filepath.Base(filepath.Dir(t.TempDir())))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(mgr.Cleanup)
|
||||
tc := &actool.ToolContext{Tasks: mgr, WorkingDir: t.TempDir(), Env: []string{"ARTEX_TEST_GUARD_CHILD=memory", "ARTEX_TEST_EXECUTABLE=" + os.Args[0]}}
|
||||
res, err := NewBash().Call(context.Background(), []byte(`{"command":"\"$ARTEX_TEST_EXECUTABLE\" -test.run='^TestGuardChild$'", "run_in_background":true, "timeout_ms":5000}`), tc)
|
||||
if err != nil || res.IsError {
|
||||
t.Fatalf("start background command: %s %v", res.Flatten(), err)
|
||||
}
|
||||
info, done := mgr.Wait(context.Background(), mgr.List()[0].ID, 7*time.Second)
|
||||
out, err := mgr.Output(info.ID, 1024)
|
||||
if !done || info.Status != actool.TaskFailed || err != nil || !strings.Contains(out, "memory limit exceeded") {
|
||||
t.Fatalf("background memory limit not surfaced: %+v, output %q, error %v", info, out, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package toolguard
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
)
|
||||
|
||||
// outputCapture keeps the first limit bytes and discards overflow. With a
|
||||
// streaming sink it forwards that bounded prefix without buffering it in RAM.
|
||||
type outputCapture struct {
|
||||
buf bytes.Buffer
|
||||
writer io.Writer
|
||||
remaining int
|
||||
truncated bool
|
||||
}
|
||||
|
||||
func newOutputCapture(limit int, stream io.Writer) *outputCapture {
|
||||
c := &outputCapture{writer: stream, remaining: limit}
|
||||
if stream == nil {
|
||||
c.writer = &c.buf
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *outputCapture) Write(p []byte) (int, error) {
|
||||
n := min(c.remaining, len(p))
|
||||
if n > 0 {
|
||||
if _, err := c.writer.Write(p[:n]); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
c.remaining -= n
|
||||
}
|
||||
c.truncated = c.truncated || n < len(p)
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
func (c *outputCapture) output() string { return c.buf.String() }
|
||||
@@ -0,0 +1,240 @@
|
||||
//go:build linux
|
||||
|
||||
package toolguard
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
cgProbeOnce sync.Once
|
||||
cgParentDir string
|
||||
cgControllers map[string]bool
|
||||
cgAttachBlocked atomic.Bool
|
||||
cgScopeCounter atomic.Uint64
|
||||
)
|
||||
|
||||
// CgroupV2Available reports whether the process can create per-command Linux
|
||||
// cgroup v2 directories with the memory controller enabled.
|
||||
func CgroupV2Available() bool {
|
||||
probeCgroupV2()
|
||||
return cgParentDir != "" && !cgAttachBlocked.Load()
|
||||
}
|
||||
|
||||
func probeCgroupV2() {
|
||||
cgProbeOnce.Do(func() {
|
||||
candidates := candidateCgroupParents()
|
||||
for _, dir := range candidates {
|
||||
ctrls := readSubtreeControllers(dir)
|
||||
if !ctrls["memory"] && !ctrls["pids"] {
|
||||
continue
|
||||
}
|
||||
probeDir := filepath.Join(dir, fmt.Sprintf("artex-probe-%d-%d", os.Getpid(), cgScopeCounter.Add(1)))
|
||||
if err := os.Mkdir(probeDir, 0o755); err != nil {
|
||||
continue
|
||||
}
|
||||
control := "pids.max"
|
||||
if ctrls["memory"] {
|
||||
control = "memory.max"
|
||||
}
|
||||
err := os.WriteFile(filepath.Join(probeDir, control), []byte("max"), 0)
|
||||
_ = os.Remove(probeDir)
|
||||
if err == nil {
|
||||
cgParentDir = dir
|
||||
cgControllers = ctrls
|
||||
return
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func candidateCgroupParents() []string {
|
||||
b, err := os.ReadFile("/proc/self/cgroup")
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
var rel string
|
||||
for _, line := range strings.Split(string(b), "\n") {
|
||||
if strings.HasPrefix(line, "0::") {
|
||||
rel = strings.TrimSpace(strings.TrimPrefix(line, "0::"))
|
||||
break
|
||||
}
|
||||
}
|
||||
if rel == "" {
|
||||
return nil
|
||||
}
|
||||
const cgRoot = "/sys/fs/cgroup"
|
||||
selfDir := filepath.Join(cgRoot, rel)
|
||||
within := func(parent, child string) bool {
|
||||
rel, err := filepath.Rel(parent, child)
|
||||
return err == nil && rel != ".." && !strings.HasPrefix(rel, "../")
|
||||
}
|
||||
if !within(cgRoot, selfDir) {
|
||||
return nil
|
||||
}
|
||||
// Never silently place a child in a sibling cgroup: this could escape
|
||||
// the service/container's existing memory and PID limits. For delegated
|
||||
// services an operator may explicitly select the enclosing subtree.
|
||||
if parent := os.Getenv(EnvToolCgroupParent); parent != "" {
|
||||
parent = filepath.Clean(parent)
|
||||
if within(cgRoot, parent) && within(parent, selfDir) {
|
||||
return []string{parent}
|
||||
}
|
||||
}
|
||||
return []string{selfDir}
|
||||
}
|
||||
|
||||
func readSubtreeControllers(dir string) map[string]bool {
|
||||
b, err := os.ReadFile(filepath.Join(dir, "cgroup.subtree_control"))
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
m := map[string]bool{}
|
||||
for _, f := range strings.Fields(string(b)) {
|
||||
m[f] = true
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
type cgroupScope struct {
|
||||
dir string
|
||||
fd int
|
||||
active bool
|
||||
}
|
||||
|
||||
func newCgroupScope(limitBytes int64, pidsLimit int) *cgroupScope {
|
||||
if limitBytes <= 0 && pidsLimit <= 0 {
|
||||
return nil
|
||||
}
|
||||
if !CgroupV2Available() || (limitBytes > 0 && !cgControllers["memory"]) ||
|
||||
(limitBytes <= 0 && !cgControllers["pids"]) {
|
||||
return nil
|
||||
}
|
||||
dir := filepath.Join(cgParentDir, fmt.Sprintf("artex-cmd-%d-%d", os.Getpid(), cgScopeCounter.Add(1)))
|
||||
if err := os.Mkdir(dir, 0o755); err != nil {
|
||||
return nil
|
||||
}
|
||||
if limitBytes > 0 {
|
||||
if err := os.WriteFile(filepath.Join(dir, "memory.max"), []byte(strconv.FormatInt(limitBytes, 10)), 0o644); err != nil {
|
||||
_ = os.Remove(dir)
|
||||
return nil
|
||||
}
|
||||
// Best effort on kernels without swap accounting. Group-wide OOM
|
||||
// termination avoids leaving sibling workers running after a kill.
|
||||
_ = os.WriteFile(filepath.Join(dir, "memory.oom.group"), []byte("1"), 0)
|
||||
_ = os.WriteFile(filepath.Join(dir, "memory.swap.max"), []byte("0"), 0)
|
||||
}
|
||||
if pidsLimit > 0 && cgControllers["pids"] {
|
||||
_ = os.WriteFile(filepath.Join(dir, "pids.max"), []byte(strconv.Itoa(pidsLimit)), 0)
|
||||
}
|
||||
scope := openCgroupScope(dir)
|
||||
if scope == nil {
|
||||
_ = os.Remove(dir)
|
||||
}
|
||||
return scope
|
||||
}
|
||||
|
||||
func openCgroupScope(dir string) *cgroupScope {
|
||||
if dir == "" {
|
||||
return nil
|
||||
}
|
||||
fd, err := syscall.Open(dir, syscall.O_RDONLY|syscall.O_DIRECTORY|syscall.O_CLOEXEC, 0)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return &cgroupScope{dir: dir, fd: fd}
|
||||
}
|
||||
|
||||
func startCommand(cmd *exec.Cmd, scope *cgroupScope) (*exec.Cmd, error) {
|
||||
if scope == nil {
|
||||
return cmd, cmd.Start()
|
||||
}
|
||||
// Start is single-use even on failure. Copy the unstarted command and
|
||||
// syscall attributes so a failed clone3 can fall back to normal exec.
|
||||
isolated := *cmd
|
||||
var attr syscall.SysProcAttr
|
||||
if cmd.SysProcAttr != nil {
|
||||
attr = *cmd.SysProcAttr
|
||||
}
|
||||
attr.UseCgroupFD, attr.CgroupFD = true, scope.fd
|
||||
isolated.SysProcAttr = &attr
|
||||
err := isolated.Start()
|
||||
if err == nil {
|
||||
scope.active = true
|
||||
return &isolated, nil
|
||||
}
|
||||
for _, unavailable := range []error{syscall.ENOSYS, syscall.EINVAL, syscall.EPERM, syscall.EACCES, syscall.EBUSY, syscall.EOPNOTSUPP} {
|
||||
if errors.Is(err, unavailable) {
|
||||
cmdErr := cmd.Start()
|
||||
if cmdErr == nil {
|
||||
cgAttachBlocked.Store(true)
|
||||
}
|
||||
return cmd, cmdErr
|
||||
}
|
||||
}
|
||||
return &isolated, err
|
||||
}
|
||||
|
||||
func (s *cgroupScope) CloseFD() {
|
||||
if s == nil || s.fd < 0 {
|
||||
return
|
||||
}
|
||||
_ = syscall.Close(s.fd)
|
||||
s.fd = -1
|
||||
}
|
||||
|
||||
func (s *cgroupScope) Kill() {
|
||||
if s == nil || s.dir == "" {
|
||||
return
|
||||
}
|
||||
// Linux >= 5.14: atomic cgroup kill.
|
||||
if err := os.WriteFile(filepath.Join(s.dir, "cgroup.kill"), []byte("1"), 0); err == nil {
|
||||
return
|
||||
}
|
||||
// Fallback for older kernels: SIGKILL every PID in cgroup.procs.
|
||||
if b, err := os.ReadFile(filepath.Join(s.dir, "cgroup.procs")); err == nil {
|
||||
for _, f := range strings.Fields(string(b)) {
|
||||
if pid, err := strconv.Atoi(f); err == nil && pid > 0 {
|
||||
_ = syscall.Kill(pid, syscall.SIGKILL)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *cgroupScope) OOMKilled() bool {
|
||||
if s == nil || s.dir == "" {
|
||||
return false
|
||||
}
|
||||
b, err := os.ReadFile(filepath.Join(s.dir, "memory.events"))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return parseCgroupMemoryEventsOOM(b)
|
||||
}
|
||||
|
||||
func (s *cgroupScope) Cleanup() {
|
||||
if s == nil {
|
||||
return
|
||||
}
|
||||
s.CloseFD()
|
||||
if s.dir == "" {
|
||||
return
|
||||
}
|
||||
s.Kill()
|
||||
for i := range 4 {
|
||||
if err := os.Remove(s.dir); err == nil || os.IsNotExist(err) {
|
||||
return
|
||||
}
|
||||
time.Sleep(time.Duration(i+1) * 15 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
//go:build linux
|
||||
|
||||
package toolguard
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestDelegatedCgroupLimitsAndCleanup(t *testing.T) {
|
||||
const limit = 24 << 20
|
||||
scope := newCgroupScope(limit, 128)
|
||||
if scope == nil {
|
||||
t.Skip("no delegated cgroup v2 subtree with the memory controller")
|
||||
}
|
||||
t.Cleanup(scope.Cleanup)
|
||||
if raw, err := os.ReadFile(filepath.Join(scope.dir, "memory.max")); err != nil || strings.TrimSpace(string(raw)) != "25165824" {
|
||||
t.Fatalf("memory.max = %q, %v", raw, err)
|
||||
}
|
||||
if cgControllers["pids"] {
|
||||
if raw, err := os.ReadFile(filepath.Join(scope.dir, "pids.max")); err != nil || strings.TrimSpace(string(raw)) != "128" {
|
||||
t.Fatalf("pids.max = %q, %v", raw, err)
|
||||
}
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
res := run(ctx, Config{MemoryLimitMB: 24}.withDefaults(), child("memory"), scope, 0, nil)
|
||||
if !scope.active {
|
||||
t.Skip("the environment blocked atomic cgroup attachment")
|
||||
}
|
||||
if !res.KilledByCgroup || !res.MemoryKilled || res.TimedOut {
|
||||
t.Fatalf("expected kernel OOM kill: %+v", res)
|
||||
}
|
||||
scope.Cleanup()
|
||||
if _, err := os.Stat(scope.dir); !os.IsNotExist(err) {
|
||||
t.Fatalf("cgroup remains after cleanup: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
//go:build !linux
|
||||
|
||||
package toolguard
|
||||
|
||||
import "os/exec"
|
||||
|
||||
func CgroupV2Available() bool { return false }
|
||||
|
||||
type cgroupScope struct {
|
||||
dir string
|
||||
active bool
|
||||
}
|
||||
|
||||
func newCgroupScope(_ int64, _ int) *cgroupScope { return nil }
|
||||
func openCgroupScope(_ string) *cgroupScope { return nil }
|
||||
func (*cgroupScope) CloseFD() {}
|
||||
func (*cgroupScope) Kill() {}
|
||||
func (*cgroupScope) OOMKilled() bool { return false }
|
||||
func (*cgroupScope) Cleanup() {}
|
||||
|
||||
func startCommand(cmd *exec.Cmd, _ *cgroupScope) (*exec.Cmd, error) {
|
||||
return cmd, cmd.Start()
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
// Package toolguard enforces per-command memory, timeout, PID, and output bounds
|
||||
// for agent Bash commands and custom command/script tools.
|
||||
package toolguard
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
EnvToolMemoryLimitMB = "ARTEX_TOOL_MEMORY_LIMIT_MB"
|
||||
EnvToolTimeoutS = "ARTEX_TOOL_TIMEOUT_S"
|
||||
EnvToolPidsLimit = "ARTEX_TOOL_PIDS_LIMIT"
|
||||
EnvToolCgroupParent = "ARTEX_TOOL_CGROUP_PARENT"
|
||||
|
||||
DefaultToolMemoryLimitMB = 2048
|
||||
DefaultToolTimeoutS = 120
|
||||
DefaultMaxToolTimeoutS = 600
|
||||
DefaultToolPidsLimit = 256
|
||||
DefaultPollInterval = 200 * time.Millisecond
|
||||
DefaultGrace = 1 * time.Second
|
||||
DefaultMaxOutputBytes = 50 << 20 // 50 MiB, matching norma's background task cap
|
||||
)
|
||||
|
||||
// Config controls per-command resource guards.
|
||||
type Config struct {
|
||||
MemoryLimitMB int // 0 disables per-command memory guard
|
||||
Timeout time.Duration // default command timeout
|
||||
MaxTimeout time.Duration // upper bound for per-call timeout_ms
|
||||
PidsLimit int // 0 disables per-command cgroup pids.max
|
||||
PollInterval time.Duration // RSS watchdog poll cadence
|
||||
Grace time.Duration // sustained over-limit duration before kill (spikes >=1.25x kill immediately)
|
||||
MaxOutputBytes int // hard cap on captured combined stdout+stderr
|
||||
}
|
||||
|
||||
// FromEnv reads the active guard configuration from environment variables,
|
||||
// falling back to safe defaults on unset or invalid values.
|
||||
func FromEnv() Config {
|
||||
memMB := parseNonNegLimit(os.Getenv(EnvToolMemoryLimitMB), DefaultToolMemoryLimitMB)
|
||||
timeoutS := parsePositiveInt(os.Getenv(EnvToolTimeoutS), DefaultToolTimeoutS)
|
||||
if int64(memMB) > math.MaxInt64/(1<<20) {
|
||||
memMB = DefaultToolMemoryLimitMB
|
||||
}
|
||||
if int64(timeoutS) > math.MaxInt64/int64(time.Second) {
|
||||
timeoutS = DefaultToolTimeoutS
|
||||
}
|
||||
pids := parseNonNegLimit(os.Getenv(EnvToolPidsLimit), DefaultToolPidsLimit)
|
||||
|
||||
maxTimeoutS := DefaultMaxToolTimeoutS
|
||||
if timeoutS > maxTimeoutS {
|
||||
maxTimeoutS = timeoutS
|
||||
}
|
||||
return Config{
|
||||
MemoryLimitMB: memMB,
|
||||
Timeout: time.Duration(timeoutS) * time.Second,
|
||||
MaxTimeout: time.Duration(maxTimeoutS) * time.Second,
|
||||
PidsLimit: pids,
|
||||
PollInterval: DefaultPollInterval,
|
||||
Grace: DefaultGrace,
|
||||
MaxOutputBytes: DefaultMaxOutputBytes,
|
||||
}
|
||||
}
|
||||
|
||||
func (c Config) withDefaults() Config {
|
||||
if c.Timeout <= 0 {
|
||||
c.Timeout = DefaultToolTimeoutS * time.Second
|
||||
}
|
||||
if c.MaxTimeout < c.Timeout {
|
||||
c.MaxTimeout = c.Timeout
|
||||
}
|
||||
if c.MaxTimeout < DefaultMaxToolTimeoutS*time.Second {
|
||||
c.MaxTimeout = DefaultMaxToolTimeoutS * time.Second
|
||||
}
|
||||
if c.PollInterval <= 0 {
|
||||
c.PollInterval = DefaultPollInterval
|
||||
}
|
||||
if c.Grace < 0 {
|
||||
c.Grace = 0
|
||||
}
|
||||
if c.MaxOutputBytes <= 0 {
|
||||
c.MaxOutputBytes = DefaultMaxOutputBytes
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// MemoryLimitBytes returns the configured per-command memory cap in bytes,
|
||||
// or 0 when disabled.
|
||||
func (c Config) MemoryLimitBytes() int64 {
|
||||
if c.MemoryLimitMB <= 0 || int64(c.MemoryLimitMB) > math.MaxInt64/(1<<20) {
|
||||
return 0
|
||||
}
|
||||
return int64(c.MemoryLimitMB) * 1024 * 1024
|
||||
}
|
||||
|
||||
// ResolveTimeout computes the effective timeout for a Bash invocation given an
|
||||
// optional model-supplied timeout_ms.
|
||||
func (c Config) ResolveTimeout(requestedMS int) time.Duration {
|
||||
c = c.withDefaults()
|
||||
if requestedMS <= 0 {
|
||||
return c.Timeout
|
||||
}
|
||||
if int64(requestedMS) > int64(c.MaxTimeout/time.Millisecond) {
|
||||
return c.MaxTimeout
|
||||
}
|
||||
return time.Duration(requestedMS) * time.Millisecond
|
||||
}
|
||||
|
||||
// RSSWatchdogAvailable reports whether sampled per-command memory enforcement is enabled.
|
||||
func (c Config) RSSWatchdogAvailable() bool { return c.MemoryLimitBytes() > 0 && watchdogAvailable() }
|
||||
|
||||
// Summary formats the active resource limits for startup logs.
|
||||
func (c Config) Summary() string {
|
||||
c = c.withDefaults()
|
||||
mem := "disabled"
|
||||
if c.MemoryLimitMB > 0 {
|
||||
mem = fmt.Sprintf("%dMiB", c.MemoryLimitMB)
|
||||
}
|
||||
pids := "disabled"
|
||||
if c.PidsLimit > 0 {
|
||||
pids = strconv.Itoa(c.PidsLimit)
|
||||
}
|
||||
return fmt.Sprintf("memory=%s timeout=%ds pids=%s (cgroup_v2=%t, rss_watchdog=%t)",
|
||||
mem, int(c.Timeout/time.Second), pids, CgroupV2Available(), c.RSSWatchdogAvailable())
|
||||
}
|
||||
|
||||
func parseNonNegLimit(raw string, def int) int {
|
||||
v := strings.ToLower(strings.TrimSpace(raw))
|
||||
if v == "" {
|
||||
return def
|
||||
}
|
||||
switch v {
|
||||
case "0", "off", "false", "disabled", "none":
|
||||
return 0
|
||||
}
|
||||
n, err := strconv.Atoi(v)
|
||||
if err != nil || n < 0 {
|
||||
return def
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func parsePositiveInt(raw string, def int) int {
|
||||
v := strings.TrimSpace(raw)
|
||||
if v == "" {
|
||||
return def
|
||||
}
|
||||
n, err := strconv.Atoi(v)
|
||||
if err != nil || n <= 0 {
|
||||
return def
|
||||
}
|
||||
return n
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package toolguard
|
||||
|
||||
import (
|
||||
"math"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestConfigFromEnv(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name, memory, timeout, pids string
|
||||
wantMemory, wantPids int
|
||||
wantTime, wantMax time.Duration
|
||||
}{
|
||||
{"defaults", "", "", "", 2048, 256, 120 * time.Second, 600 * time.Second},
|
||||
{"override", "64", "700", "32", 64, 32, 700 * time.Second, 700 * time.Second},
|
||||
{"disabled", "0", "8", "off", 0, 0, 8 * time.Second, 600 * time.Second},
|
||||
{"invalid", "-5", "999999999999999999", "abc", 2048, 256, 120 * time.Second, 600 * time.Second},
|
||||
{"overflow", "999999999999999999", "0", "-5", 2048, 256, 120 * time.Second, 600 * time.Second},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Setenv(EnvToolMemoryLimitMB, tc.memory)
|
||||
t.Setenv(EnvToolTimeoutS, tc.timeout)
|
||||
t.Setenv(EnvToolPidsLimit, tc.pids)
|
||||
c := FromEnv()
|
||||
if c.MemoryLimitBytes() != int64(tc.wantMemory)<<20 || c.PidsLimit != tc.wantPids ||
|
||||
c.ResolveTimeout(0) != tc.wantTime || c.ResolveTimeout(math.MaxInt) != tc.wantMax ||
|
||||
c.ResolveTimeout(125) != 125*time.Millisecond {
|
||||
t.Fatalf("unexpected settings: %+v", c)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
//go:build darwin || freebsd || openbsd || netbsd
|
||||
|
||||
package toolguard
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os/exec"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func watchdogAvailable() bool { return true }
|
||||
|
||||
// readProcessTreeMemory samples the command's descendants and group, excluding
|
||||
// the guard helper itself for background commands.
|
||||
func readProcessTreeMemory(rootPID, groupID, excludePID int) (int64, []int, bool) {
|
||||
if rootPID <= 0 {
|
||||
return 0, nil, false
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
out, err := exec.CommandContext(ctx, "/bin/ps", "-axo", "pid=,ppid=,pgid=,rss=").Output()
|
||||
if err != nil {
|
||||
return 0, nil, false
|
||||
}
|
||||
var entries []procEntry
|
||||
byPID := make(map[int]int64, 64)
|
||||
rootAlive := false
|
||||
for _, line := range strings.Split(string(out), "\n") {
|
||||
f := strings.Fields(line)
|
||||
if len(f) < 4 {
|
||||
continue
|
||||
}
|
||||
pid, e1 := strconv.Atoi(f[0])
|
||||
ppid, e2 := strconv.Atoi(f[1])
|
||||
pgrp, e3 := strconv.Atoi(f[2])
|
||||
rssKB, e4 := strconv.ParseInt(f[3], 10, 64)
|
||||
if e1 != nil || e2 != nil || e3 != nil || e4 != nil || pid <= 0 {
|
||||
continue
|
||||
}
|
||||
if pid == rootPID || (pgrp == groupID && pid != excludePID) {
|
||||
rootAlive = true
|
||||
}
|
||||
rssBytes := rssKB * 1024
|
||||
entries = append(entries, procEntry{pid: pid, ppid: ppid, pgrp: pgrp})
|
||||
byPID[pid] = rssBytes
|
||||
}
|
||||
if !rootAlive {
|
||||
return 0, nil, false
|
||||
}
|
||||
pids := collectTreePIDs(rootPID, groupID, excludePID, entries)
|
||||
var total int64
|
||||
for _, pid := range pids {
|
||||
total += byPID[pid]
|
||||
}
|
||||
return total, pids, true
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
//go:build linux
|
||||
|
||||
package toolguard
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
func watchdogAvailable() bool { return true }
|
||||
|
||||
// readProcessTreeMemory samples the command's descendants and group, excluding
|
||||
// the guard helper itself for background commands.
|
||||
func readProcessTreeMemory(rootPID, groupID, excludePID int) (int64, []int, bool) {
|
||||
if rootPID <= 0 {
|
||||
return 0, nil, false
|
||||
}
|
||||
dirs, err := os.ReadDir("/proc")
|
||||
if err != nil {
|
||||
return 0, nil, false
|
||||
}
|
||||
entries := make([]procEntry, 0, len(dirs))
|
||||
rootAlive := false
|
||||
for _, d := range dirs {
|
||||
if !d.IsDir() {
|
||||
continue
|
||||
}
|
||||
pid, err := strconv.Atoi(d.Name())
|
||||
if err != nil || pid <= 0 {
|
||||
continue
|
||||
}
|
||||
statBytes, err := os.ReadFile(filepath.Join("/proc", d.Name(), "stat"))
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
ppid, pgrp, ok := parseProcStat(statBytes)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if pid == rootPID || (pgrp == groupID && pid != excludePID) {
|
||||
rootAlive = true
|
||||
}
|
||||
entries = append(entries, procEntry{pid: pid, ppid: ppid, pgrp: pgrp})
|
||||
}
|
||||
if !rootAlive {
|
||||
return 0, nil, false
|
||||
}
|
||||
pids := collectTreePIDs(rootPID, groupID, excludePID, entries)
|
||||
var total int64
|
||||
var anyRead bool
|
||||
for _, pid := range pids {
|
||||
pidStr := strconv.Itoa(pid)
|
||||
if b, err := os.ReadFile(filepath.Join("/proc", pidStr, "status")); err == nil {
|
||||
if n, ok := parseProcStatusBytes(b); ok {
|
||||
total += n
|
||||
anyRead = true
|
||||
}
|
||||
}
|
||||
}
|
||||
return total, pids, anyRead
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
//go:build !linux && !darwin && !freebsd && !openbsd && !netbsd
|
||||
|
||||
package toolguard
|
||||
|
||||
func watchdogAvailable() bool { return false }
|
||||
|
||||
func readProcessTreeMemory(_, _, _ int) (int64, []int, bool) {
|
||||
return 0, nil, false
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package toolguard
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type procEntry struct {
|
||||
pid int
|
||||
ppid int
|
||||
pgrp int
|
||||
}
|
||||
|
||||
// collectTreePIDs returns every PID belonging to rootPID's process group or
|
||||
// descending from rootPID (or from any member of that process group).
|
||||
func collectTreePIDs(rootPID, groupID, excludePID int, entries []procEntry) []int {
|
||||
if rootPID <= 0 {
|
||||
return nil
|
||||
}
|
||||
children := make(map[int][]int, len(entries))
|
||||
seen := map[int]bool{rootPID: true}
|
||||
queue := []int{rootPID}
|
||||
for _, e := range entries {
|
||||
if e.pid <= 0 {
|
||||
continue
|
||||
}
|
||||
children[e.ppid] = append(children[e.ppid], e.pid)
|
||||
if e.pgrp == groupID && e.pid != excludePID && !seen[e.pid] {
|
||||
seen[e.pid] = true
|
||||
queue = append(queue, e.pid)
|
||||
}
|
||||
}
|
||||
for i := 0; i < len(queue); i++ {
|
||||
cur := queue[i]
|
||||
for _, ch := range children[cur] {
|
||||
if !seen[ch] {
|
||||
seen[ch] = true
|
||||
queue = append(queue, ch)
|
||||
}
|
||||
}
|
||||
}
|
||||
return queue
|
||||
}
|
||||
|
||||
// parseProcStat parses Linux /proc/<pid>/stat, returning (ppid, pgrp, ok).
|
||||
// The process name inside parentheses may contain spaces or ')', so we locate
|
||||
// the last ')' before splitting the trailing fields.
|
||||
func parseProcStat(data []byte) (ppid, pgrp int, ok bool) {
|
||||
idx := bytes.LastIndexByte(data, ')')
|
||||
if idx < 0 || idx+2 >= len(data) {
|
||||
return 0, 0, false
|
||||
}
|
||||
fields := strings.Fields(string(data[idx+1:]))
|
||||
// fields[0] = state, fields[1] = ppid, fields[2] = pgrp
|
||||
if len(fields) < 3 {
|
||||
return 0, 0, false
|
||||
}
|
||||
pp, err1 := strconv.Atoi(fields[1])
|
||||
pg, err2 := strconv.Atoi(fields[2])
|
||||
if err1 != nil || err2 != nil {
|
||||
return 0, 0, false
|
||||
}
|
||||
return pp, pg, true
|
||||
}
|
||||
|
||||
// parseProcStatusBytes parses Linux /proc/<pid>/status and returns
|
||||
// (VmRSS + VmSwap) in bytes.
|
||||
func parseProcStatusBytes(data []byte) (int64, bool) {
|
||||
var rssKB, swapKB int64
|
||||
var sawRSS bool
|
||||
for _, line := range strings.Split(string(data), "\n") {
|
||||
switch {
|
||||
case strings.HasPrefix(line, "VmRSS:"):
|
||||
if v, ok := parseKBField(line); ok {
|
||||
rssKB = v
|
||||
sawRSS = true
|
||||
}
|
||||
case strings.HasPrefix(line, "VmSwap:"):
|
||||
if v, ok := parseKBField(line); ok {
|
||||
swapKB = v
|
||||
}
|
||||
}
|
||||
}
|
||||
if !sawRSS {
|
||||
return 0, false
|
||||
}
|
||||
return (rssKB + swapKB) * 1024, true
|
||||
}
|
||||
|
||||
func parseKBField(line string) (int64, bool) {
|
||||
f := strings.Fields(line)
|
||||
if len(f) < 2 {
|
||||
return 0, false
|
||||
}
|
||||
n, err := strconv.ParseInt(f[1], 10, 64)
|
||||
if err != nil || n < 0 {
|
||||
return 0, false
|
||||
}
|
||||
return n, true
|
||||
}
|
||||
|
||||
// parseCgroupMemoryEventsOOM reports whether a Linux cgroup v2 memory.events
|
||||
// payload shows any kernel OOM kill event.
|
||||
func parseCgroupMemoryEventsOOM(data []byte) bool {
|
||||
for _, line := range strings.Split(string(data), "\n") {
|
||||
f := strings.Fields(line)
|
||||
if len(f) == 2 && f[0] == "oom_kill" {
|
||||
if n, err := strconv.ParseInt(f[1], 10, 64); err == nil && n > 0 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
//go:build !windows
|
||||
|
||||
package toolguard
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
func setProcessGroup(cmd *exec.Cmd) {
|
||||
if cmd.SysProcAttr == nil {
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{}
|
||||
}
|
||||
cmd.SysProcAttr.Setpgid = true
|
||||
}
|
||||
|
||||
func killProcessGroup(process *os.Process) {
|
||||
_ = syscall.Kill(-process.Pid, syscall.SIGKILL)
|
||||
}
|
||||
|
||||
func killProcessIDs(pids []int) {
|
||||
for _, pid := range pids {
|
||||
_ = syscall.Kill(pid, syscall.SIGKILL)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
//go:build windows
|
||||
|
||||
package toolguard
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
func setProcessGroup(_ *exec.Cmd) {}
|
||||
|
||||
func killProcessGroup(p *os.Process) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
_ = exec.CommandContext(ctx, "taskkill", "/T", "/F", "/PID", strconv.Itoa(p.Pid)).Run()
|
||||
_ = p.Kill()
|
||||
}
|
||||
|
||||
func killProcessIDs(_ []int) {}
|
||||
@@ -0,0 +1,173 @@
|
||||
package toolguard
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"runtime"
|
||||
"time"
|
||||
)
|
||||
|
||||
// RunResult holds the outcome of a guarded subprocess execution.
|
||||
type RunResult struct {
|
||||
Output string
|
||||
OutputTruncated bool
|
||||
ExitCode int
|
||||
TimedOut bool
|
||||
MemoryKilled bool
|
||||
KilledByCgroup bool
|
||||
PeakMemoryBytes int64
|
||||
MemoryLimitBytes int64
|
||||
Err error
|
||||
}
|
||||
|
||||
// Run executes a one-shot subprocess and cleans up its process group when done.
|
||||
// The caller supplies the deadline, if any. cmd must not have been started.
|
||||
func Run(ctx context.Context, cfg Config, cmd *exec.Cmd) RunResult {
|
||||
cfg = cfg.withDefaults()
|
||||
scope := newCgroupScope(cfg.MemoryLimitBytes(), cfg.PidsLimit)
|
||||
if scope != nil {
|
||||
defer scope.Cleanup()
|
||||
}
|
||||
return run(ctx, cfg, cmd, scope, 0, nil)
|
||||
}
|
||||
|
||||
// group is zero for foreground commands. A background helper runs its command
|
||||
// within its own existing process group, so norma's TaskStop can kill both.
|
||||
func run(ctx context.Context, cfg Config, cmd *exec.Cmd, scope *cgroupScope, group int, stream io.Writer) RunResult {
|
||||
res := RunResult{ExitCode: -1, MemoryLimitBytes: cfg.MemoryLimitBytes()}
|
||||
if err := ctx.Err(); err != nil {
|
||||
res.Err, res.TimedOut = err, errors.Is(err, context.DeadlineExceeded)
|
||||
return res
|
||||
}
|
||||
if group == 0 {
|
||||
setProcessGroup(cmd)
|
||||
}
|
||||
|
||||
// Own the combined output pipe so Wait observes the direct child exiting,
|
||||
// even if a descendant still has stdout/stderr open.
|
||||
r, w, err := os.Pipe()
|
||||
if err != nil {
|
||||
res.Err = err
|
||||
return res
|
||||
}
|
||||
defer r.Close()
|
||||
defer w.Close()
|
||||
cmd.Stdout, cmd.Stderr = w, w
|
||||
cmd.WaitDelay = time.Second // also bounds os/exec's stdin pump, if present
|
||||
cmd, err = startCommand(cmd, scope)
|
||||
if scope != nil {
|
||||
scope.CloseFD()
|
||||
}
|
||||
if err != nil {
|
||||
res.Err = err
|
||||
return res
|
||||
}
|
||||
_ = w.Close()
|
||||
|
||||
capture := newOutputCapture(cfg.MaxOutputBytes, stream)
|
||||
drained := make(chan struct{})
|
||||
go func() {
|
||||
_, _ = io.Copy(capture, r)
|
||||
close(drained)
|
||||
}()
|
||||
waited := make(chan error, 1)
|
||||
go func() { waited <- cmd.Wait() }()
|
||||
|
||||
root := cmd.Process.Pid
|
||||
groupID := root
|
||||
if group != 0 {
|
||||
groupID = group
|
||||
}
|
||||
// When delegated memory.max is active, the kernel enforces the bound and
|
||||
// we do not need to walk /proc. Fall back to the sampled watchdog otherwise.
|
||||
var samples <-chan time.Time
|
||||
if res.MemoryLimitBytes > 0 && (scope == nil || !scope.active) && watchdogAvailable() {
|
||||
ticker := time.NewTicker(cfg.PollInterval)
|
||||
defer ticker.Stop()
|
||||
samples = ticker.C
|
||||
}
|
||||
kill := func(exited bool) {
|
||||
if scope != nil && scope.active {
|
||||
scope.Kill()
|
||||
}
|
||||
if group == 0 {
|
||||
if runtime.GOOS == "windows" && exited {
|
||||
return
|
||||
}
|
||||
killProcessGroup(cmd.Process)
|
||||
} else if scope == nil || !scope.active {
|
||||
// Do not kill the background helper itself: it still needs to
|
||||
// print the resource-limit error to the task's output file.
|
||||
_, pids, _ := readProcessTreeMemory(root, groupID, group)
|
||||
killProcessIDs(pids)
|
||||
_ = cmd.Process.Kill()
|
||||
}
|
||||
}
|
||||
|
||||
var overSince time.Time
|
||||
wait:
|
||||
for {
|
||||
select {
|
||||
case res.Err = <-waited:
|
||||
kill(true) // one-shot commands must not leave workers behind
|
||||
break wait
|
||||
case <-ctx.Done():
|
||||
res.TimedOut = errors.Is(ctx.Err(), context.DeadlineExceeded)
|
||||
kill(false)
|
||||
<-waited
|
||||
res.Err = ctx.Err()
|
||||
break wait
|
||||
case now := <-samples:
|
||||
used, pids, ok := readProcessTreeMemory(root, groupID, group)
|
||||
if !ok || used <= res.MemoryLimitBytes {
|
||||
overSince = time.Time{}
|
||||
continue
|
||||
}
|
||||
res.PeakMemoryBytes = max(res.PeakMemoryBytes, used)
|
||||
if overSince.IsZero() {
|
||||
overSince = now
|
||||
}
|
||||
if used-res.MemoryLimitBytes >= res.MemoryLimitBytes/4 || now.Sub(overSince) >= cfg.Grace {
|
||||
res.MemoryKilled = true
|
||||
if group == 0 {
|
||||
// Include freshly observed descendants that changed process groups.
|
||||
killProcessIDs(pids)
|
||||
}
|
||||
kill(false)
|
||||
res.Err = <-waited
|
||||
break wait
|
||||
}
|
||||
}
|
||||
}
|
||||
res.KilledByCgroup = scope != nil && scope.active && scope.OOMKilled()
|
||||
res.MemoryKilled = res.MemoryKilled || res.KilledByCgroup
|
||||
if res.MemoryKilled {
|
||||
res.TimedOut = false
|
||||
}
|
||||
res.ExitCode = cmd.ProcessState.ExitCode()
|
||||
|
||||
// Bound drain time even if an untracked process inherited the output pipe.
|
||||
drainTimer := time.NewTimer(time.Second)
|
||||
defer drainTimer.Stop()
|
||||
select {
|
||||
case <-drained:
|
||||
case <-drainTimer.C:
|
||||
_ = r.Close()
|
||||
<-drained
|
||||
}
|
||||
res.Output, res.OutputTruncated = capture.output(), capture.truncated
|
||||
return res
|
||||
}
|
||||
|
||||
// FormatMemoryKilled returns a model-actionable termination reason.
|
||||
func FormatMemoryKilled(peakBytes, limitBytes int64, byCgroup bool) string {
|
||||
const mib = 1 << 20
|
||||
if byCgroup {
|
||||
return fmt.Sprintf("[command killed: memory limit exceeded (cgroup cap %d MiB; reduce memory usage or adjust %s)]", limitBytes/mib, EnvToolMemoryLimitMB)
|
||||
}
|
||||
return fmt.Sprintf("[command killed: memory limit exceeded (sampled %.1f MiB, limit %d MiB; reduce memory usage or adjust %s)]", float64(peakBytes)/mib, limitBytes/mib, EnvToolMemoryLimitMB)
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package toolguard
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
if code, handled := BackgroundHelper(os.Args[1:]); handled {
|
||||
os.Exit(code)
|
||||
}
|
||||
os.Exit(m.Run())
|
||||
}
|
||||
|
||||
func TestGuardChild(t *testing.T) {
|
||||
// Use a fixed-size child workload, never a machine-wide stress test.
|
||||
switch os.Getenv("ARTEX_TEST_GUARD_CHILD") {
|
||||
case "memory":
|
||||
b := make([]byte, 48<<20)
|
||||
for i := 0; i < len(b); i += os.Getpagesize() {
|
||||
b[i] = 1
|
||||
}
|
||||
fmt.Println("allocated")
|
||||
time.Sleep(10 * time.Second)
|
||||
runtime.KeepAlive(b)
|
||||
case "output":
|
||||
fmt.Fprint(os.Stdout, "stdout")
|
||||
fmt.Fprint(os.Stderr, "stderr")
|
||||
os.Exit(7)
|
||||
case "sleep":
|
||||
time.Sleep(10 * time.Second)
|
||||
}
|
||||
}
|
||||
|
||||
func child(mode string) *exec.Cmd {
|
||||
cmd := exec.Command(os.Args[0], "-test.run=^TestGuardChild$")
|
||||
cmd.Env = append(os.Environ(), "ARTEX_TEST_GUARD_CHILD="+mode)
|
||||
return cmd
|
||||
}
|
||||
|
||||
func TestRunOutputAndExitCode(t *testing.T) {
|
||||
res := Run(context.Background(), Config{MaxOutputBytes: 8}, child("output"))
|
||||
if res.Output != "stdoutst" || !res.OutputTruncated || res.ExitCode != 7 || res.Err == nil {
|
||||
t.Fatalf("unexpected result: %+v", res)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunDoesNotStartCancelledCommand(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
cmd := child("output")
|
||||
res := Run(ctx, Config{}, cmd)
|
||||
if cmd.Process != nil || !errors.Is(res.Err, context.Canceled) {
|
||||
t.Fatalf("unexpected result: %+v", res)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunTimeout(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
|
||||
defer cancel()
|
||||
res := Run(ctx, Config{}, child("sleep"))
|
||||
if !res.TimedOut || res.MemoryKilled || !errors.Is(res.Err, context.DeadlineExceeded) {
|
||||
t.Fatalf("unexpected result: %+v", res)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWatchdogLimitsDescendantMemory(t *testing.T) {
|
||||
if !watchdogAvailable() {
|
||||
t.Skip("no process memory watchdog on this platform")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
cmd := exec.Command("bash", "-c", `"$1" -test.run='^TestGuardChild$' & wait`, "guard-test", os.Args[0])
|
||||
cmd.Env = append(os.Environ(), "ARTEX_TEST_GUARD_CHILD=memory")
|
||||
cfg := Config{MemoryLimitMB: 16, PollInterval: 30 * time.Millisecond}.withDefaults()
|
||||
// Explicitly exercise the fallback even if this host has delegated cgroups.
|
||||
res := run(ctx, cfg, cmd, nil, 0, nil)
|
||||
if !res.MemoryKilled || res.KilledByCgroup || res.TimedOut || res.PeakMemoryBytes <= 16<<20 {
|
||||
t.Fatalf("expected watchdog to terminate the process tree: %+v", res)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunDoesNotLeaveBackgroundChildren(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("Unix process-group cleanup")
|
||||
}
|
||||
marker := filepath.Join(t.TempDir(), "child-survived")
|
||||
cmd := exec.Command("bash", "-c", `(sleep 0.4; touch "$1") & printf done`, "guard-test", marker)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
res := Run(ctx, Config{}, cmd)
|
||||
if res.Err != nil || res.Output != "done" {
|
||||
t.Fatalf("unexpected result: %+v", res)
|
||||
}
|
||||
time.Sleep(550 * time.Millisecond)
|
||||
if _, err := os.Stat(marker); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("command left descendants running: stat = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProcParsing(t *testing.T) {
|
||||
if pp, pg, ok := parseProcStat([]byte("12 (name with ) inside) S 10 11 7")); !ok || pp != 10 || pg != 11 {
|
||||
t.Fatalf("unexpected stat parse: %d %d %t", pp, pg, ok)
|
||||
}
|
||||
if n, ok := parseProcStatusBytes([]byte("Name:\ttest\nVmRSS:\t400 kB\nVmSwap:\t20 kB\n")); !ok || n != 420*1024 {
|
||||
t.Fatalf("unexpected status parse: %d %t", n, ok)
|
||||
}
|
||||
if got := collectTreePIDs(11, 10, 10, []procEntry{
|
||||
{pid: 10, pgrp: 10}, {pid: 11, ppid: 10, pgrp: 10}, {pid: 12, ppid: 11, pgrp: 12},
|
||||
{pid: 13, ppid: 1, pgrp: 10}, {pid: 14, ppid: 1, pgrp: 14},
|
||||
}); !reflect.DeepEqual(got, []int{11, 13, 12}) {
|
||||
t.Fatalf("unexpected group: %v", got)
|
||||
}
|
||||
if !parseCgroupMemoryEventsOOM([]byte("oom 2\noom_kill 1\n")) || parseCgroupMemoryEventsOOM([]byte("oom 2\noom_kill 0\n")) {
|
||||
t.Fatal("only a positive oom_kill counter should be reported")
|
||||
}
|
||||
if note := FormatMemoryKilled(0, 16<<20, true); !strings.Contains(note, "memory limit exceeded") || !strings.Contains(note, "16 MiB") {
|
||||
t.Fatalf("unexpected cgroup error: %q", note)
|
||||
}
|
||||
}
|
||||
+29
-17
@@ -6,6 +6,7 @@ import (
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
@@ -19,6 +20,7 @@ import (
|
||||
|
||||
"github.com/Autumn-27/artex/db"
|
||||
"github.com/Autumn-27/artex/internal/httpidentity"
|
||||
"github.com/Autumn-27/artex/internal/toolguard"
|
||||
"github.com/Autumn-27/norma/permission"
|
||||
actool "github.com/Autumn-27/norma/tool"
|
||||
)
|
||||
@@ -336,15 +338,14 @@ func (s *Server) runCommandTool(ctx context.Context, execRaw json.RawMessage, pa
|
||||
return actool.Errorf("command 为空"), nil
|
||||
}
|
||||
cmd := renderTemplate(spec.Command, params, shellQuote)
|
||||
// 复用 Bash 也在用的底层 run(经 Bash CoreTool.Call):自动继承安全 floor/超时/
|
||||
// 代理 env/输出溢出。工具与 Bash 平级、共用底层,不经过 Bash 这个工具让模型调。
|
||||
bashIn, _ := json.Marshal(map[string]any{"command": cmd})
|
||||
// 复用受资源上限保护的 Bash 底层 run:自动继承安全 floor / 内存与超时限制 /
|
||||
// 代理 env / 输出溢出。工具与 Bash 平级、共用底层,不经过 Bash 这个工具让模型调。
|
||||
payload := map[string]any{"command": cmd}
|
||||
if spec.TimeoutMs > 0 {
|
||||
var cancel context.CancelFunc
|
||||
ctx, cancel = context.WithTimeout(ctx, timeoutOr(spec.TimeoutMs, 120000))
|
||||
defer cancel()
|
||||
payload["timeout_ms"] = spec.TimeoutMs
|
||||
}
|
||||
return actool.NewBash().Call(ctx, bashIn, tc)
|
||||
bashIn, _ := json.Marshal(payload)
|
||||
return toolguard.NewBash().Call(ctx, bashIn, tc)
|
||||
}
|
||||
|
||||
// ---------- script(仅 Python):临时文件 + stdin JSON + env ----------
|
||||
@@ -367,16 +368,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, timeoutOr(spec.TimeoutMs, 120000))
|
||||
body, err := execPython(ctx, interp, key, spec.Code, params, workDir, sessionEnv, toolguard.FromEnv().ResolveTimeout(spec.TimeoutMs))
|
||||
if err != nil {
|
||||
return actool.Errorf(maskSecrets(err.Error())), nil
|
||||
out := actool.Capture(tc, body)
|
||||
if out != "" {
|
||||
out += "\n\n"
|
||||
}
|
||||
return actool.Errorf(out + maskSecrets(err.Error())), nil
|
||||
}
|
||||
return actool.Text(actool.Capture(tc, body)), nil
|
||||
}
|
||||
|
||||
// execPython writes the code to a temp .py under workDir/.tools, runs it via interp
|
||||
// with the params JSON on stdin + scalar params mirrored to TOOL_<NAME> env, and
|
||||
// returns combined stdout+stderr (with a timeout/exit note). Standalone + testable.
|
||||
// returns combined stdout+stderr and any termination error.
|
||||
func execPython(ctx context.Context, interp, key, code string, params map[string]any, workDir string, sessionEnv []string, timeout time.Duration) (string, error) {
|
||||
toolsDir := filepath.Join(workDir, ".tools")
|
||||
if err := os.MkdirAll(toolsDir, 0o755); err != nil {
|
||||
@@ -396,7 +401,7 @@ func execPython(ctx context.Context, interp, key, code string, params map[string
|
||||
|
||||
runCtx, cancel := context.WithTimeout(ctx, timeout)
|
||||
defer cancel()
|
||||
c := exec.CommandContext(runCtx, interp, tmp)
|
||||
c := exec.Command(interp, tmp)
|
||||
c.Dir = workDir
|
||||
c.Env = append(os.Environ(), sessionEnv...) // 会话代理 env
|
||||
for k, v := range params { // 标量参数镜像成 TOOL_<NAME>
|
||||
@@ -406,12 +411,19 @@ func execPython(ctx context.Context, interp, key, code string, params map[string
|
||||
}
|
||||
pj, _ := json.Marshal(params)
|
||||
c.Stdin = bytes.NewReader(pj) // 参数 JSON 走 stdin
|
||||
out, err := c.CombinedOutput()
|
||||
body := string(out)
|
||||
if runCtx.Err() == context.DeadlineExceeded {
|
||||
body += "\n... [超时终止] ..."
|
||||
} else if err != nil {
|
||||
body += "\n[exit: " + err.Error() + "]"
|
||||
res := toolguard.Run(runCtx, toolguard.FromEnv(), c)
|
||||
body := res.Output
|
||||
if res.OutputTruncated {
|
||||
body += "\n\n[output truncated at capture limit]"
|
||||
}
|
||||
if res.MemoryKilled {
|
||||
return body, errors.New(toolguard.FormatMemoryKilled(res.PeakMemoryBytes, res.MemoryLimitBytes, res.KilledByCgroup))
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os/exec"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -185,3 +186,32 @@ func TestHTTPToolTruncatesLargeBody(t *testing.T) {
|
||||
t.Fatalf("oversized http body was not truncated: len=%d", len(out))
|
||||
}
|
||||
}
|
||||
|
||||
func TestCustomCommandToolTimeout(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("POSIX shell syntax")
|
||||
}
|
||||
s := &Server{}
|
||||
res, err := s.runCommandTool(context.Background(), []byte(`{"command":"sleep 10", "timeout_ms":100}`), nil, nil)
|
||||
if err != nil || !res.IsError || !strings.Contains(res.Flatten(), "timed out") {
|
||||
t.Fatalf("expected timeout, got %s, %v", res.Flatten(), err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecPythonMemoryLimit(t *testing.T) {
|
||||
if runtime.GOOS != "linux" && runtime.GOOS != "darwin" {
|
||||
t.Skip("requires a process memory watchdog")
|
||||
}
|
||||
interp, err := exec.LookPath("python3")
|
||||
if err != nil {
|
||||
t.Skip("python3 unavailable")
|
||||
}
|
||||
t.Setenv("ARTEX_TOOL_MEMORY_LIMIT_MB", "16")
|
||||
_, err = execPython(context.Background(), interp, "test", `import time
|
||||
b = bytearray(b'x') * (48 * 1024 * 1024)
|
||||
time.sleep(10)
|
||||
`, nil, t.TempDir(), nil, 5*time.Second)
|
||||
if err == nil || !strings.Contains(err.Error(), "memory limit exceeded") {
|
||||
t.Fatalf("expected a memory limit error, got %v", err)
|
||||
}
|
||||
}
|
||||
@@ -140,8 +140,8 @@ func (s *Server) mcpTools() []mcpTool {
|
||||
},
|
||||
{
|
||||
Name: "resume_task", Scope: db.APIScopeTaskControl,
|
||||
Description: "恢复已暂停的任务,或原地重新打开已结束(done/failed/timeout)且仍有未完成目标或待执行(open)意图的任务。并发已满时任务会进入排队(status=queued)。",
|
||||
Schema: objSchema(map[string]any{"task_id": strParam("要恢复/重新打开的任务 id")}, "task_id"),
|
||||
Description: "恢复已暂停的任务。并发已满时任务会进入排队(status=queued)。",
|
||||
Schema: objSchema(map[string]any{"task_id": strParam("要恢复的任务 id")}, "task_id"),
|
||||
Run: func(_ context.Context, token *db.APIToken, in json.RawMessage) (actool.Result, error) {
|
||||
return s.mcpControlTask(token, in, "resume")
|
||||
},
|
||||
@@ -524,15 +524,7 @@ func (s *Server) mcpControlTask(token *db.APIToken, in json.RawMessage, action s
|
||||
if t == nil {
|
||||
return failure, nil
|
||||
}
|
||||
var (
|
||||
out taskControlResult
|
||||
err error
|
||||
)
|
||||
if action == "resume" {
|
||||
out, err = s.resumeOrReopenTask(t, agent.AbortPausedByOrchestrator)
|
||||
} else {
|
||||
out, err = s.applyTaskControlWithCause(t, action, agent.AbortPausedByOrchestrator)
|
||||
}
|
||||
out, err := s.applyTaskControlWithCause(t, action, agent.AbortPausedByOrchestrator)
|
||||
if err != nil {
|
||||
return actool.Errorf(err.Error()), nil
|
||||
}
|
||||
|
||||
+11
-158
@@ -69,12 +69,9 @@ func (s *Server) orchestrationTools() []actool.CoreTool {
|
||||
s.toolListLLMProfiles(),
|
||||
s.toolSpawnTask(),
|
||||
s.toolPauseTask(),
|
||||
s.toolResumeTask(),
|
||||
s.toolGetTaskGraph(),
|
||||
s.toolListTaskFindings(),
|
||||
s.toolAddHint(),
|
||||
s.toolSetTaskGoals(),
|
||||
s.toolAddTaskIntent(),
|
||||
s.toolGetWorkerTrace(),
|
||||
s.toolListWorkerTraces(),
|
||||
s.toolSearchWorkerTraces(),
|
||||
@@ -150,20 +147,6 @@ func wrTool(name, desc string, schema map[string]any, run func(context.Context,
|
||||
// delegateToTask resolves the `task_id` in the input, builds a ToolSet bound to
|
||||
// that task's store, strips task_id, and calls the chosen per-task tool — so the
|
||||
// cross-task read reuses the exact in-task logic against another task.
|
||||
func (s *Server) lookupTask(raw string) (*Task, bool) {
|
||||
trimmed := strings.TrimSpace(raw)
|
||||
if trimmed == "" {
|
||||
return nil, false
|
||||
}
|
||||
if t, ok := s.m.Task(trimmed); ok {
|
||||
return t, true
|
||||
}
|
||||
if id, ok := canonicalTaskID(trimmed); ok {
|
||||
return s.m.Task(id)
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
func (s *Server) delegateToTask(ctx context.Context, in json.RawMessage, pick func(*agent.ToolSet) actool.CoreTool) (actool.Result, error) {
|
||||
var head struct {
|
||||
TaskID string `json:"task_id"`
|
||||
@@ -172,31 +155,20 @@ func (s *Server) delegateToTask(ctx context.Context, in json.RawMessage, pick fu
|
||||
if strings.TrimSpace(head.TaskID) == "" {
|
||||
return actool.Errorf("task_id 为必填"), nil
|
||||
}
|
||||
t, ok := s.lookupTask(head.TaskID)
|
||||
t, ok := s.m.Task(head.TaskID)
|
||||
if !ok {
|
||||
return actool.Errorf("task 不存在: " + head.TaskID), nil
|
||||
}
|
||||
if s.engine != nil {
|
||||
if !s.engine.beginTaskOperation(t.ID) {
|
||||
return actool.Errorf("任务正在删除,无法操作: " + t.ID), nil
|
||||
}
|
||||
defer s.engine.decInflight(t.ID)
|
||||
}
|
||||
var m map[string]json.RawMessage
|
||||
_ = json.Unmarshal(in, &m)
|
||||
delete(m, "task_id")
|
||||
inner, _ := json.Marshal(m)
|
||||
tsx := agent.NewToolSet(t.Store, "orchestrator")
|
||||
if taskIDInt, err := strconv.ParseInt(t.ID, 10, 64); err == nil && taskIDInt > 0 {
|
||||
tsx.SetTaskID(taskIDInt)
|
||||
}
|
||||
if s.m.Assets() != nil {
|
||||
tsx.SetAssetStore(s.m.Assets(), s.m.Assets().Companies())
|
||||
}
|
||||
tsx.SetNotify(t.Notify) // 通用唤醒(无专用回调的写操作走它;读工具为 no-op)
|
||||
tsx.SetResumeTask(func() { s.reviveTask(t) }) // set_task_goals / add_task_intent → 把已完成/暂停的任务拉回 running
|
||||
tsx.SetNotifyGoal(t.NotifyGoal) // set_task_goals → 记一条「人新增了 N 个目标:…」触发并唤醒 planner
|
||||
tsx.SetNotifyHint(t.NotifyHint) // add_hint → 记一条「人新增了 N 条战略提示:…」触发并唤醒 planner
|
||||
tsx.SetNotify(t.Notify) // 通用唤醒(无专用回调的写操作走它;读工具为 no-op)
|
||||
tsx.SetNotifyHint(t.NotifyHint) // add_hint → 记一条「人新增了 N 条战略提示:…」触发并唤醒 planner
|
||||
return pick(tsx).Call(ctx, inner, nil)
|
||||
}
|
||||
|
||||
@@ -407,39 +379,6 @@ func (s *Server) toolPauseTask() actool.CoreTool {
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) toolResumeTask() actool.CoreTool {
|
||||
return wrTool("resume_task",
|
||||
"恢复已暂停的任务,或原地重新打开已结束(done/failed/timeout)且仍有未完成目标或待执行(open)意图的任务继续运行(保留已有探索图、发现与 frontier,不新建重复任务)。当用户要求继续/重开已有任务时,优先使用本工具(或 set_task_goals / add_task_intent),不要用 spawn_task 另起重复任务。",
|
||||
objSchema(map[string]any{"task_id": strParam("要恢复/重新打开的任务 id;在任务内主 Agent 对话中可省略(默认当前任务)")}),
|
||||
func(ctx context.Context, in json.RawMessage) (actool.Result, error) {
|
||||
var a struct {
|
||||
TaskID string `json:"task_id"`
|
||||
}
|
||||
_ = json.Unmarshal(in, &a)
|
||||
rawID := strings.TrimSpace(a.TaskID)
|
||||
if info := agent.RunInfoFrom(ctx); info.TaskID > 0 {
|
||||
curID := strconv.FormatInt(info.TaskID, 10)
|
||||
if rawID == "" {
|
||||
rawID = curID
|
||||
} else if canon, ok := canonicalTaskID(rawID); !ok || canon != curID {
|
||||
return actool.Errorf(fmt.Sprintf("当前在任务 #%s 上下文中,只能恢复当前任务", curID)), nil
|
||||
}
|
||||
}
|
||||
if rawID == "" {
|
||||
return actool.Errorf("task_id 为必填"), nil
|
||||
}
|
||||
t, ok := s.lookupTask(rawID)
|
||||
if !ok {
|
||||
return actool.Errorf("task 不存在: " + rawID), nil
|
||||
}
|
||||
res, err := s.resumeOrReopenTask(t, agent.AbortPausedByOrchestrator)
|
||||
if err != nil {
|
||||
return actool.Errorf(err.Error()), nil
|
||||
}
|
||||
return jsonResult(map[string]any{"task_id": t.ID, "status": res.Status, "queued": res.Queued})
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) toolGetTaskGraph() actool.CoreTool {
|
||||
return roTool("get_task_graph", "读指定任务的探索图总览(同 graph_overview:资产计数/frontier/发现/覆盖等),用 task_id 指定任务。",
|
||||
objSchema(map[string]any{"task_id": strParam("任务 id")}, "task_id"),
|
||||
@@ -471,38 +410,6 @@ func (s *Server) toolAddHint() actool.CoreTool {
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) toolSetTaskGoals() actool.CoreTool {
|
||||
return wrTool("set_task_goals",
|
||||
"给指定任务新增探索目标(goal),写入任务图并自动把已完成/暂停的任务拉回运行态继续规划执行(保留已有图谱与发现,无需另起新任务)。\n"+
|
||||
"★优先批量:多个目标放进 goals 数组一次提交(返回 ids 与之等长同序,失败项 id=0,详情见 errors);单条则省略 goals 直接给顶层 text。",
|
||||
objSchema(map[string]any{
|
||||
"task_id": strParam("任务 id"),
|
||||
"goals": map[string]any{"type": "array", "description": "【优先用这个】要新增的目标数组,按顺序处理。每个元素:text(必填,一个独立可验证的最终目标)+ vulnclass(可选)。", "items": objSchema(map[string]any{"text": strParam("一个独立可验证的最终目标"), "vulnclass": strParam("可选:对应漏洞类,如 SQLi/IDOR")}, "text")},
|
||||
"text": strParam("[单条] 一个独立可验证的最终目标"),
|
||||
"vulnclass": strParam("[单条] 对应漏洞类(若明确),如 SQLi/IDOR;业务逻辑目标可留空"),
|
||||
}, "task_id"),
|
||||
func(ctx context.Context, in json.RawMessage) (actool.Result, error) {
|
||||
return s.delegateToTask(ctx, in, (*agent.ToolSet).SetGoalsTool)
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) toolAddTaskIntent() actool.CoreTool {
|
||||
return wrTool("add_task_intent",
|
||||
"给指定任务直接下发探索意图(intent)写入 frontier,并自动把已完成/暂停的任务拉回运行态让 worker 领取执行(保留已有图谱与发现,无需另起新任务)。\n"+
|
||||
"★优先批量:多个方向放进 intents 数组一次提交(返回 ids 与之等长同序,失败项 id=0,详情见 errors);单条则省略 intents 直接给顶层 summary。",
|
||||
objSchema(map[string]any{
|
||||
"task_id": strParam("任务 id"),
|
||||
"intents": map[string]any{"type": "array", "description": "【优先用这个】要新增的探索方向数组,每个元素字段同顶层(summary/asset_ids/parent_ids/priority)。", "items": objSchema(map[string]any{"summary": strParam("探索方向摘要"), "asset_ids": map[string]any{"type": "array", "items": map[string]any{"type": "integer"}}, "parent_ids": map[string]any{"type": "array", "items": map[string]any{"type": "integer"}}, "priority": map[string]any{"type": "integer"}}, "summary")},
|
||||
"summary": strParam("[单条] 一句话描述这个探索方向:做什么+为什么"),
|
||||
"asset_ids": map[string]any{"type": "array", "items": map[string]any{"type": "integer"}, "description": "目标资产 id(可选,0/1/多个)"},
|
||||
"parent_ids": map[string]any{"type": "array", "items": map[string]any{"type": "integer"}, "description": "上游锚点 fact/finding 节点 id(可选,0/1/多个;顶层全新方向请留空)"},
|
||||
"priority": map[string]any{"type": "integer", "description": "优先级 0-10,默认 5;直投紧急意图建议 8-10"},
|
||||
}, "task_id"),
|
||||
func(ctx context.Context, in json.RawMessage) (actool.Result, error) {
|
||||
return s.delegateToTask(ctx, in, (*agent.ToolSet).AddIntentTool)
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) toolGetWorkerTrace() actool.CoreTool {
|
||||
return roTool("get_task_worker_trace",
|
||||
"看指定任务里某个 work(意图)的执行过程:get_task_worker_trace(task_id, intent_id) 看步骤摘要;再带 step_ids=[...] 取那几步完整内容(一次最多 5 个,多传只返回前 5 个)。",
|
||||
@@ -614,24 +521,17 @@ func (s *Server) deriveTaskStatus(t *Task) string {
|
||||
// orchestrationToolSeeds seeds the cross-task tools into the tools table so they
|
||||
// are bindable per-agent (default: bound to nobody — opt-in for orchestration
|
||||
// agents). First-insert only, like the traffic seeds.
|
||||
func defaultOrchestrationToolBindings(name string) json.RawMessage {
|
||||
switch {
|
||||
case name == "resume_task":
|
||||
return json.RawMessage(`["auto","mainagent"]`)
|
||||
case name == "bind_finding_traffic" || strings.Contains(name, "finding_case") || name == "search_finding_duplicates" || name == "get_finding_record" || name == "merge_finding_records" || name == "suggest_finding_merge":
|
||||
return json.RawMessage(`["reporter"]`)
|
||||
default:
|
||||
return json.RawMessage(`["auto"]`)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) seedOrchestrationTools() {
|
||||
// task-op + platform tools default-bind to the built-in Auto agent (它天生用来
|
||||
// 操作平台)。SeedTool 首插入生效;老库已 seed 的行由 seedAutoDefaultBindings 补绑。
|
||||
autoAgents, _ := json.Marshal([]string{"auto"})
|
||||
for _, t := range s.orchestrationTools() {
|
||||
schema, _ := json.Marshal(t.InputSchema())
|
||||
_ = s.m.PG().SeedTool(t.Name(), t.Description(), schema, defaultOrchestrationToolBindings(t.Name()))
|
||||
bindings := autoAgents
|
||||
if t.Name() == "bind_finding_traffic" || strings.Contains(t.Name(), "finding_case") || t.Name() == "search_finding_duplicates" || t.Name() == "get_finding_record" || t.Name() == "merge_finding_records" || t.Name() == "suggest_finding_merge" {
|
||||
bindings = json.RawMessage(`["reporter"]`)
|
||||
}
|
||||
_ = s.m.PG().SeedTool(t.Name(), t.Description(), schema, bindings)
|
||||
}
|
||||
for _, t := range s.platformTools() {
|
||||
schema, _ := json.Marshal(t.InputSchema())
|
||||
@@ -639,7 +539,6 @@ func (s *Server) seedOrchestrationTools() {
|
||||
}
|
||||
s.refreshBuiltinToolSchemas()
|
||||
s.seedAutoDefaultBindings()
|
||||
s.seedTaskReopenBindings()
|
||||
s.seedPlannerDefaultBindings()
|
||||
s.seedPlannerListAssetsBinding()
|
||||
s.seedCompanyScopeRebind()
|
||||
@@ -648,8 +547,7 @@ func (s *Server) seedOrchestrationTools() {
|
||||
s.seedAutoReportFindingBinding()
|
||||
s.unbindGoalMetDefault()
|
||||
s.reseedGoalsPrompt() // goals 提示词加入「抽操作约束」步 → 旧库追加一版新默认(一次性)
|
||||
s.reseedAutoPrompt() // auto 提示词加入 resume_task/set_task_goals/add_task_intent 与原地继续原则(一次性)
|
||||
s.reseedMainAgentPrompt() // mainagent 提示词加入 resume_task 引导(一次性)
|
||||
s.reseedMainAgentPrompt() // mainagent 提示词加入「目标达成后 add_intent 反问是否建目标」(一次性)
|
||||
s.reseedPlannerPrompt() // planner 提示词:重写「0 意图」正当理由 + 加量化验收核对(一次性)
|
||||
s.reseedWorkerPrompt() // worker 提示词:加否定结论证据门槛(一次性)
|
||||
s.seedReporterAgent() // 预置「报告撰写」agent + 工具绑定 + finding 触发器(一次性)
|
||||
@@ -731,7 +629,7 @@ func (s *Server) migrateReporterWorkflow() {
|
||||
// reaches an old DB otherwise. Preserves each tool's agent binding + enabled flag.
|
||||
// Bump the flag whenever these tools' schemas/descriptions change in code.
|
||||
func (s *Server) refreshBuiltinToolSchemas() {
|
||||
const flag = "tool_schema_refresh_v9_task_reopen_tools"
|
||||
const flag = "tool_schema_refresh_v8_finding_case_tools"
|
||||
if v, _, _ := s.m.pg.GetSetting(flag); v == "true" {
|
||||
return
|
||||
}
|
||||
@@ -816,7 +714,7 @@ func (s *Server) reseedGoalsPrompt() {
|
||||
// 保留在历史里,用户若自定义过可从版本记录找回。settings flag 守卫 → 只做一次。全新库无需处理
|
||||
// (SeedPromptIfEmpty 已 seed 最新默认)。与 reseedGoalsPrompt 完全同构。
|
||||
func (s *Server) reseedMainAgentPrompt() {
|
||||
const flag = "mainagent_prompt_task_reopen_v2"
|
||||
const flag = "mainagent_prompt_goalless_intent_v1"
|
||||
if v, _, _ := s.m.pg.GetSetting(flag); v == "true" {
|
||||
return
|
||||
}
|
||||
@@ -840,32 +738,6 @@ func (s *Server) reseedMainAgentPrompt() {
|
||||
log.Printf("[prompts] mainagent 提示词已追加新默认版本(加入目标达成后反问建目标,一次性)")
|
||||
}
|
||||
|
||||
// reseedAutoPrompt 把 auto 提示词刷成【当前代码默认】——加入 resume_task /
|
||||
// set_task_goals / add_task_intent 以及「原地继续优先于新建任务」原则。
|
||||
func (s *Server) reseedAutoPrompt() {
|
||||
const flag = "auto_prompt_task_reopen_v1"
|
||||
if v, _, _ := s.m.pg.GetSetting(flag); v == "true" {
|
||||
return
|
||||
}
|
||||
defer func() { _ = s.m.pg.SetSetting(flag, "true") }()
|
||||
a, err := s.m.pg.GetAgentByKey("auto")
|
||||
if err != nil || a == nil {
|
||||
return
|
||||
}
|
||||
tmpl := agent.BuiltinPromptSeeds()["auto"]
|
||||
if tmpl == "" {
|
||||
return
|
||||
}
|
||||
if cur, err := s.m.pg.CurrentPrompt(a.ID); err == nil && cur == tmpl {
|
||||
return
|
||||
}
|
||||
if _, err := s.m.pg.ResetPromptToDefault(a.ID, tmpl); err != nil {
|
||||
log.Printf("[prompts] auto 提示词重刷为新默认失败: %v", err)
|
||||
return
|
||||
}
|
||||
log.Printf("[prompts] auto 提示词已追加新默认版本(加入 resume_task/set_task_goals/add_task_intent,一次性)")
|
||||
}
|
||||
|
||||
// reseedPlannerPrompt 把 planner 提示词刷成【当前代码默认】——默认正文做了精简重构,并把「克制」降级为
|
||||
// 仅去重、新增「深度优先于覆盖度」「硬底线:目标未达成且无在跑意图必须产出」、给否定结论复核加上界。
|
||||
// 每次默认有实质变更就 bump 下面的 flag(当前 v2)让存量旧库再刷一次。SeedPromptIfEmpty 首插入only,旧库已有版本收不到,故用版本管理
|
||||
@@ -1161,22 +1033,3 @@ func (s *Server) seedAutoDefaultBindings() {
|
||||
}
|
||||
_ = s.m.pg.SetSetting(flag, "true")
|
||||
}
|
||||
|
||||
// seedTaskReopenBindings adds the task reopen/steering orchestration tools to
|
||||
// existing DBs ONCE (guarded by a settings flag), without re-adding unrelated
|
||||
// tools a user may have deliberately unbound.
|
||||
func (s *Server) seedTaskReopenBindings() {
|
||||
const flag = "task_reopen_bindings_v1"
|
||||
if v, _, _ := s.m.pg.GetSetting(flag); v == "true" {
|
||||
return
|
||||
}
|
||||
if err := s.m.pg.AddAgentToToolBinding("auto", []string{"resume_task", "set_task_goals", "add_task_intent"}); err != nil {
|
||||
log.Printf("[auto] 任务重开/操舵工具默认绑定失败: %v", err)
|
||||
return
|
||||
}
|
||||
if err := s.m.pg.AddAgentToToolBinding("mainagent", []string{"resume_task"}); err != nil {
|
||||
log.Printf("[mainagent] resume_task 默认绑定失败: %v", err)
|
||||
return
|
||||
}
|
||||
_ = s.m.pg.SetSetting(flag, "true")
|
||||
}
|
||||
@@ -910,7 +910,6 @@ func (s *Server) Handler() http.Handler {
|
||||
mux.HandleFunc("PATCH /api/tasks/{id}/constraints/{cid}", s.editConstraint) // 约束管理:修改约束
|
||||
mux.HandleFunc("DELETE /api/tasks/{id}/constraints/{cid}", s.deleteConstraint) // 约束管理:删除约束
|
||||
mux.HandleFunc("POST /api/tasks/{id}/control", s.control)
|
||||
mux.HandleFunc("POST /api/tasks/{id}/resume", s.resumeTask)
|
||||
mux.HandleFunc("PUT /api/tasks/{id}/llm", s.updateTaskLLMProfiles)
|
||||
mux.HandleFunc("GET /api/tasks/{id}/llm/resolution", s.taskLLMResolutionHandler)
|
||||
mux.HandleFunc("POST /api/tasks/{id}/intents/{iid}/control", s.controlIntent)
|
||||
@@ -1390,22 +1389,6 @@ func (s *Server) control(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, 200, result)
|
||||
}
|
||||
|
||||
// resumeTask resumes a paused task or reopens a terminal task (done/failed/timeout)
|
||||
// in place when it still has open goals or open intents.
|
||||
func (s *Server) resumeTask(w http.ResponseWriter, r *http.Request) {
|
||||
t, ok := s.lookupTask(r.PathValue("id"))
|
||||
if !ok {
|
||||
writeErr(w, 404, "task not found")
|
||||
return
|
||||
}
|
||||
result, err := s.resumeOrReopenTask(t, agent.AbortPausedByUser)
|
||||
if err != nil {
|
||||
writeErr(w, 409, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, result)
|
||||
}
|
||||
|
||||
// controlIntent pauses, resumes, or cancels one local worker intent. A running
|
||||
// worker is always stopped before state mutation/cleanup, preventing tool output
|
||||
// that arrives after the user action from recreating deleted blackboard records.
|
||||
|
||||
+2
-15
@@ -840,22 +840,9 @@ func (s *Server) pgResetTool(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, 200, map[string]any{"ok": true})
|
||||
return
|
||||
}
|
||||
// orchestration tools use per-tool default bindings (auto / auto+mainagent / reporter).
|
||||
for _, t := range s.orchestrationTools() {
|
||||
if t.Name() != key {
|
||||
continue
|
||||
}
|
||||
schema, _ := json.Marshal(t.InputSchema())
|
||||
if err := pg.UpsertToolForce(t.Name(), t.Description(), schema, defaultOrchestrationToolBindings(t.Name())); err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"ok": true})
|
||||
return
|
||||
}
|
||||
// platform tools (auto agent) — default-bind to "auto".
|
||||
// orchestration/platform tools (auto agent) — default-bind to "auto".
|
||||
autoAgents, _ := json.Marshal([]string{"auto"})
|
||||
for _, t := range s.platformTools() {
|
||||
for _, t := range append(s.orchestrationTools(), s.platformTools()...) {
|
||||
if t.Name() != key {
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -4,6 +4,8 @@ import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/Autumn-27/artex/internal/toolguard"
|
||||
)
|
||||
|
||||
type metricValue struct {
|
||||
@@ -12,15 +14,38 @@ type metricValue struct {
|
||||
Percent float64 `json:"percent"`
|
||||
}
|
||||
|
||||
type resourceLimitsInfo struct {
|
||||
ContainerMemoryLimitBytes uint64 `json:"container_memory_limit_bytes"`
|
||||
ContainerMemoryBounded bool `json:"container_memory_bounded"`
|
||||
ContainerPidsLimit uint64 `json:"container_pids_limit"`
|
||||
ToolMemoryLimitMB int `json:"tool_memory_limit_mb"`
|
||||
ToolTimeoutSeconds int `json:"tool_timeout_seconds"`
|
||||
ToolPidsLimit int `json:"tool_pids_limit"`
|
||||
ToolCgroupAvailable bool `json:"tool_cgroup_available"`
|
||||
ToolRSSWatchdogAvailable bool `json:"tool_rss_watchdog_available"`
|
||||
}
|
||||
|
||||
type systemMetricsResponse struct {
|
||||
Scope string `json:"scope"`
|
||||
Supported bool `json:"supported"`
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
CPU metricValue `json:"cpu"`
|
||||
Memory metricValue `json:"memory"`
|
||||
Disk metricValue `json:"disk"`
|
||||
DataDisk metricValue `json:"data_disk"`
|
||||
Container bool `json:"container_metrics"`
|
||||
Scope string `json:"scope"`
|
||||
Supported bool `json:"supported"`
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
CPU metricValue `json:"cpu"`
|
||||
Memory metricValue `json:"memory"`
|
||||
Disk metricValue `json:"disk"`
|
||||
DataDisk metricValue `json:"data_disk"`
|
||||
Container bool `json:"container_metrics"`
|
||||
Limits resourceLimitsInfo `json:"limits"`
|
||||
}
|
||||
|
||||
func toolResourceLimits() resourceLimitsInfo {
|
||||
cfg := toolguard.FromEnv()
|
||||
return resourceLimitsInfo{
|
||||
ToolMemoryLimitMB: cfg.MemoryLimitMB,
|
||||
ToolTimeoutSeconds: int(cfg.Timeout / time.Second),
|
||||
ToolPidsLimit: cfg.PidsLimit,
|
||||
ToolCgroupAvailable: toolguard.CgroupV2Available(),
|
||||
ToolRSSWatchdogAvailable: cfg.RSSWatchdogAvailable(),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) systemMetrics(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
+145
-22
@@ -20,43 +20,166 @@ func systemMetricsSnapshot(s *Server) systemMetricsResponse {
|
||||
s.metricsMu.Lock()
|
||||
if !s.lastCPUAt.IsZero() && use >= s.lastCPUUse && limit > 0 {
|
||||
elapsed := now.Sub(s.lastCPUAt).Seconds()
|
||||
if elapsed > 0 { cpuPct = float64(use-s.lastCPUUse) / 1e6 / elapsed / limit * 100 }
|
||||
if elapsed > 0 {
|
||||
cpuPct = float64(use-s.lastCPUUse) / 1e6 / elapsed / limit * 100
|
||||
}
|
||||
}
|
||||
s.lastCPUUse, s.lastCPUAt = use, now
|
||||
s.metricsMu.Unlock()
|
||||
}
|
||||
memUsed, memTotal, memOK := cgroupMemory()
|
||||
memoryDirs := cgroupControllerDirs("memory")
|
||||
memoryLimit := cgroupLimit(memoryDirs, "memory.max", "memory.limit_in_bytes")
|
||||
pidsLimit := cgroupLimit(cgroupControllerDirs("pids"), "pids.max", "pids.max")
|
||||
memUsed, memOK := cgroupMemoryUsage(memoryDirs)
|
||||
memTotal := memoryLimit
|
||||
if memOK && memTotal == 0 {
|
||||
memTotal = hostMemoryTotal()
|
||||
}
|
||||
root, data := diskMetric("/"), diskMetric(s.dataDir)
|
||||
if data.TotalBytes == 0 { data = root }
|
||||
if data.TotalBytes == 0 {
|
||||
data = root
|
||||
}
|
||||
limits := toolResourceLimits()
|
||||
limits.ContainerMemoryLimitBytes = memoryLimit
|
||||
limits.ContainerMemoryBounded = memoryLimit > 0
|
||||
limits.ContainerPidsLimit = pidsLimit
|
||||
return systemMetricsResponse{Scope: "container", Supported: true, Timestamp: time.Now().UTC(), Container: cpuOK || memOK,
|
||||
CPU: metricValue{Percent: clampPercent(cpuPct)}, Memory: metricValue{UsedBytes: memUsed, TotalBytes: memTotal, Percent: percent(memUsed, memTotal)}, Disk: root, DataDisk: data}
|
||||
CPU: metricValue{Percent: clampPercent(cpuPct)}, Memory: metricValue{UsedBytes: memUsed, TotalBytes: memTotal, Percent: percent(memUsed, memTotal)}, Disk: root, DataDisk: data,
|
||||
Limits: limits}
|
||||
}
|
||||
|
||||
func cgroupCPU() (uint64, float64, bool) {
|
||||
for _, dir := range []string{"/sys/fs/cgroup", "/sys/fs/cgroup/cpu"} {
|
||||
b, err := os.ReadFile(filepath.Join(dir, "cpu.stat")); if err != nil { continue }
|
||||
b, err := os.ReadFile(filepath.Join(dir, "cpu.stat"))
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
var use uint64
|
||||
for _, line := range strings.Split(string(b), "\n") { f := strings.Fields(line); if len(f) == 2 && f[0] == "usage_usec" { use, _ = strconv.ParseUint(f[1], 10, 64) } }
|
||||
for _, line := range strings.Split(string(b), "\n") {
|
||||
f := strings.Fields(line)
|
||||
if len(f) == 2 && f[0] == "usage_usec" {
|
||||
use, _ = strconv.ParseUint(f[1], 10, 64)
|
||||
}
|
||||
}
|
||||
limit := float64(runtime.NumCPU())
|
||||
if q, err := os.ReadFile(filepath.Join(dir, "cpu.max")); err == nil { f := strings.Fields(string(q)); if len(f) == 2 && f[0] != "max" { quota, _ := strconv.ParseFloat(f[0], 64); period, _ := strconv.ParseFloat(f[1], 64); if period > 0 { limit = quota / period } } }
|
||||
if use > 0 { return use, limit, true }
|
||||
if q, err := os.ReadFile(filepath.Join(dir, "cpu.max")); err == nil {
|
||||
f := strings.Fields(string(q))
|
||||
if len(f) == 2 && f[0] != "max" {
|
||||
quota, _ := strconv.ParseFloat(f[0], 64)
|
||||
period, _ := strconv.ParseFloat(f[1], 64)
|
||||
if period > 0 {
|
||||
limit = quota / period
|
||||
}
|
||||
}
|
||||
}
|
||||
if use > 0 {
|
||||
return use, limit, true
|
||||
}
|
||||
}
|
||||
return 0, 0, false
|
||||
}
|
||||
|
||||
func cgroupMemory() (uint64, uint64, bool) {
|
||||
for _, dir := range []string{"/sys/fs/cgroup", "/sys/fs/cgroup/memory"} {
|
||||
cur, ce := readUint(filepath.Join(dir, "memory.current")); max, me := readUint(filepath.Join(dir, "memory.max"))
|
||||
if ce == nil && me == nil { return cur, max, max > 0 }
|
||||
if ce == nil { if b, err := os.ReadFile(filepath.Join(dir, "memory.max")); err == nil && strings.TrimSpace(string(b)) == "max" { return cur, hostMemoryTotal(), true } }
|
||||
cur, ce = readUint(filepath.Join(dir, "memory.usage_in_bytes")); max, me = readUint(filepath.Join(dir, "memory.limit_in_bytes"))
|
||||
if ce == nil && me == nil && max < ^uint64(0)/2 { return cur, max, true }
|
||||
}
|
||||
return 0, 0, false
|
||||
type controllerDirs struct {
|
||||
root string
|
||||
leaf string
|
||||
v2 bool
|
||||
}
|
||||
|
||||
func hostMemoryTotal() uint64 { b, err := os.ReadFile("/proc/meminfo"); if err != nil { return 0 }; for _, line := range strings.Split(string(b), "\n") { f := strings.Fields(line); if len(f) >= 2 && f[0] == "MemTotal:" { n, _ := strconv.ParseUint(f[1], 10, 64); return n * 1024 } }; return 0 }
|
||||
func readUint(path string) (uint64, error) { b, err := os.ReadFile(path); if err != nil { return 0, err }; return strconv.ParseUint(strings.TrimSpace(string(b)), 10, 64) }
|
||||
func diskMetric(path string) metricValue { var st syscall.Statfs_t; if path == "" || syscall.Statfs(path, &st) != nil { return metricValue{} }; total, free := st.Blocks*uint64(st.Bsize), st.Bavail*uint64(st.Bsize); used := total-free; return metricValue{UsedBytes: used, TotalBytes: total, Percent: percent(used, total)} }
|
||||
func percent(used, total uint64) float64 { if total == 0 { return 0 }; return clampPercent(float64(used)/float64(total)*100) }
|
||||
func clampPercent(v float64) float64 { if v < 0 { return 0 }; if v > 100 { return 100 }; return v }
|
||||
func cgroupControllerDirs(controller string) controllerDirs {
|
||||
const mount = "/sys/fs/cgroup"
|
||||
data, _ := os.ReadFile("/proc/self/cgroup")
|
||||
for _, line := range strings.Split(string(data), "\n") {
|
||||
f := strings.SplitN(line, ":", 3)
|
||||
if len(f) != 3 || !strings.HasPrefix(f[2], "/") {
|
||||
continue
|
||||
}
|
||||
if f[0] == "0" && f[1] == "" {
|
||||
return controllerDirs{root: mount, leaf: filepath.Join(mount, filepath.Clean(f[2])), v2: true}
|
||||
}
|
||||
if strings.Contains(","+f[1]+",", ","+controller+",") {
|
||||
root := filepath.Join(mount, controller)
|
||||
return controllerDirs{root: root, leaf: filepath.Join(root, filepath.Clean(f[2]))}
|
||||
}
|
||||
}
|
||||
return controllerDirs{}
|
||||
}
|
||||
|
||||
func cgroupMemoryUsage(d controllerDirs) (uint64, bool) {
|
||||
if d.leaf == "" {
|
||||
return 0, false
|
||||
}
|
||||
name := "memory.usage_in_bytes"
|
||||
if d.v2 {
|
||||
name = "memory.current"
|
||||
}
|
||||
n, err := readUint(filepath.Join(d.leaf, name))
|
||||
return n, err == nil
|
||||
}
|
||||
|
||||
// The effective bound is the smallest finite limit from leaf to mount root.
|
||||
func cgroupLimit(d controllerDirs, v2Name, v1Name string) uint64 {
|
||||
if d.leaf == "" {
|
||||
return 0
|
||||
}
|
||||
name := v1Name
|
||||
if d.v2 {
|
||||
name = v2Name
|
||||
}
|
||||
var limit uint64
|
||||
for dir := d.leaf; ; dir = filepath.Dir(dir) {
|
||||
n, err := readUint(filepath.Join(dir, name))
|
||||
// v1 represents unlimited memory with a large page-aligned sentinel.
|
||||
if err == nil && n > 0 && (d.v2 || name != "memory.limit_in_bytes" || n < 1<<62) && (limit == 0 || n < limit) {
|
||||
limit = n
|
||||
}
|
||||
if dir == d.root || dir == filepath.Dir(dir) {
|
||||
return limit
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func hostMemoryTotal() uint64 {
|
||||
b, err := os.ReadFile("/proc/meminfo")
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
for _, line := range strings.Split(string(b), "\n") {
|
||||
f := strings.Fields(line)
|
||||
if len(f) >= 2 && f[0] == "MemTotal:" {
|
||||
n, _ := strconv.ParseUint(f[1], 10, 64)
|
||||
return n * 1024
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
func readUint(path string) (uint64, error) {
|
||||
b, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return strconv.ParseUint(strings.TrimSpace(string(b)), 10, 64)
|
||||
}
|
||||
func diskMetric(path string) metricValue {
|
||||
var st syscall.Statfs_t
|
||||
if path == "" || syscall.Statfs(path, &st) != nil {
|
||||
return metricValue{}
|
||||
}
|
||||
total, free := st.Blocks*uint64(st.Bsize), st.Bavail*uint64(st.Bsize)
|
||||
used := total - free
|
||||
return metricValue{UsedBytes: used, TotalBytes: total, Percent: percent(used, total)}
|
||||
}
|
||||
func percent(used, total uint64) float64 {
|
||||
if total == 0 {
|
||||
return 0
|
||||
}
|
||||
return clampPercent(float64(used) / float64(total) * 100)
|
||||
}
|
||||
func clampPercent(v float64) float64 {
|
||||
if v < 0 {
|
||||
return 0
|
||||
}
|
||||
if v > 100 {
|
||||
return 100
|
||||
}
|
||||
return v
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
//go:build linux
|
||||
|
||||
package server
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCgroupEffectiveLimit(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
parent := filepath.Join(root, "container")
|
||||
leaf := filepath.Join(parent, "app")
|
||||
if err := os.MkdirAll(leaf, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
write := func(dir, name, value string) {
|
||||
t.Helper()
|
||||
if err := os.WriteFile(filepath.Join(dir, name), []byte(value), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
write(leaf, "memory.max", "max\n")
|
||||
write(parent, "memory.max", "1073741824\n")
|
||||
write(root, "memory.max", "2147483648\n")
|
||||
write(leaf, "pids.max", "48\n")
|
||||
write(parent, "pids.max", "64\n")
|
||||
d := controllerDirs{root: root, leaf: leaf, v2: true}
|
||||
if got := cgroupLimit(d, "memory.max", "memory.limit_in_bytes"); got != 1<<30 {
|
||||
t.Fatalf("expected parent's memory limit, got %d", got)
|
||||
}
|
||||
if got := cgroupLimit(d, "pids.max", "pids.max"); got != 48 {
|
||||
t.Fatalf("expected the smaller leaf PID limit, got %d", got)
|
||||
}
|
||||
write(leaf, "memory.limit_in_bytes", "9223372036854771712\n")
|
||||
d.v2 = false
|
||||
if got := cgroupLimit(d, "memory.max", "memory.limit_in_bytes"); got != 0 {
|
||||
t.Fatalf("v1 unlimited sentinel reported as a bound: %d", got)
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,9 @@ import (
|
||||
)
|
||||
|
||||
func TestSystemMetricsReturnsContainerAndDiskValues(t *testing.T) {
|
||||
t.Setenv("ARTEX_TOOL_MEMORY_LIMIT_MB", "96")
|
||||
t.Setenv("ARTEX_TOOL_TIMEOUT_S", "72")
|
||||
t.Setenv("ARTEX_TOOL_PIDS_LIMIT", "48")
|
||||
s := &Server{dataDir: t.TempDir()}
|
||||
r := httptest.NewRequest("GET", "/api/system/metrics", nil)
|
||||
w := httptest.NewRecorder()
|
||||
@@ -22,6 +25,9 @@ func TestSystemMetricsReturnsContainerAndDiskValues(t *testing.T) {
|
||||
if got.Scope == "" || got.Timestamp.IsZero() {
|
||||
t.Fatalf("unexpected response metadata: %+v", got)
|
||||
}
|
||||
if got.Limits.ToolMemoryLimitMB != 96 || got.Limits.ToolTimeoutSeconds != 72 || got.Limits.ToolPidsLimit != 48 {
|
||||
t.Fatalf("configured tool limits missing: %+v", got.Limits)
|
||||
}
|
||||
if runtime.GOOS != "linux" {
|
||||
if got.Supported || got.Scope != "unsupported" {
|
||||
t.Fatalf("unsupported platform returned metrics: %+v", got)
|
||||
|
||||
@@ -5,5 +5,10 @@ package server
|
||||
import "time"
|
||||
|
||||
func systemMetricsSnapshot(_ *Server) systemMetricsResponse {
|
||||
return systemMetricsResponse{Scope: "unsupported", Supported: false, Timestamp: time.Now().UTC()}
|
||||
return systemMetricsResponse{
|
||||
Scope: "unsupported",
|
||||
Supported: false,
|
||||
Timestamp: time.Now().UTC(),
|
||||
Limits: toolResourceLimits(),
|
||||
}
|
||||
}
|
||||
@@ -193,88 +193,6 @@ func (s *Server) applyTaskControlWithCause(t *Task, action string, pauseCause er
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// resumeOrReopenTask resumes a paused task or reopens a terminal
|
||||
// (done/failed/timeout) task in place when it still has open goals or open
|
||||
// intents to execute. Unlike applyTaskControl("resume"), which stays strictly
|
||||
// paused-only for schedule/proxy/batch control callers, this is the explicit
|
||||
// operator/agent reopen path (POST /api/tasks/{id}/resume and resume_task).
|
||||
func (s *Server) resumeOrReopenTask(t *Task, cause error) (taskControlResult, error) {
|
||||
if t == nil {
|
||||
return taskControlResult{}, fmt.Errorf("task not found")
|
||||
}
|
||||
out := taskControlResult{ID: t.ID}
|
||||
lifecycle := t.lifecycleSnapshot()
|
||||
if !isTerminalStatus(lifecycle.Status) {
|
||||
if lifecycle.Paused || s.engine.IsPaused(t.ID) {
|
||||
return s.applyTaskControlWithCause(t, "resume", cause)
|
||||
}
|
||||
if lifecycle.Queued {
|
||||
return out, fmt.Errorf("任务当前已在排队等待运行,无需恢复")
|
||||
}
|
||||
if s.engine.Started(t.ID) {
|
||||
return out, fmt.Errorf("任务当前正在运行,无需恢复")
|
||||
}
|
||||
mode := s.resumeAdmissionMode(t)
|
||||
queued, err := s.admitTask(t, mode)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
out.Queued = queued
|
||||
out.Status = map[bool]string{true: "queued", false: "running"}[queued]
|
||||
return out, nil
|
||||
}
|
||||
|
||||
if !s.engine.beginTaskOperation(t.ID) {
|
||||
return out, fmt.Errorf("任务正在删除,无法恢复")
|
||||
}
|
||||
defer s.engine.decInflight(t.ID)
|
||||
|
||||
current, exists := s.m.Task(t.ID)
|
||||
if !exists || current != t || s.engine.IsDeleting(t.ID) {
|
||||
return out, fmt.Errorf("任务正在删除,无法恢复")
|
||||
}
|
||||
lifecycle = t.lifecycleSnapshot()
|
||||
if !isTerminalStatus(lifecycle.Status) {
|
||||
if lifecycle.Paused || s.engine.IsPaused(t.ID) {
|
||||
return s.applyTaskControlWithCause(t, "resume", cause)
|
||||
}
|
||||
out.Queued = lifecycle.Queued
|
||||
out.Status = s.deriveTaskStatus(t)
|
||||
return out, nil
|
||||
}
|
||||
|
||||
hasOpenGoal, err := t.Store.HasOpenGoal()
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
hasActiveIntent, err := t.Store.HasActiveIntent()
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
mode := "resume"
|
||||
if !hasOpenGoal && !hasActiveIntent {
|
||||
goals, gErr := t.Store.ListByKind(db.KindGoal, 1)
|
||||
if gErr == nil && len(goals) == 0 && lifecycle.FirstRunAt == 0 {
|
||||
mode = "bootstrap"
|
||||
} else {
|
||||
return out, fmt.Errorf("任务所有目标均已达成且没有待执行(open)的意图,无法直接恢复;请先通过 set_goals/set_task_goals 新增目标,或通过 add_intent/add_task_intent 下发新意图(系统会自动将任务拉回运行态)")
|
||||
}
|
||||
}
|
||||
queued, err := s.admitTask(t, mode)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
out.Queued = queued
|
||||
out.Status = map[bool]string{true: "queued", false: "running"}[queued]
|
||||
summary := "任务已重新打开,继续执行剩余探索任务"
|
||||
if queued {
|
||||
summary = "任务已重新打开并进入排队,等待运行槽位"
|
||||
}
|
||||
s.engine.emitActivity(t, db.Activity{Worker: "system", Kind: "text", Summary: summary})
|
||||
log.Printf("[task] #%s 已重新打开继续运行 (from=%s status=%s)", t.ID, lifecycle.Status, out.Status)
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// intentSummaryOf 取意图 payload 里的 summary,供删除通知在意图节点消失(真删除)前留档。
|
||||
func intentSummaryOf(n *db.Node) string {
|
||||
if n == nil {
|
||||
|
||||
@@ -1,438 +0,0 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Autumn-27/artex/agent"
|
||||
"github.com/Autumn-27/artex/db"
|
||||
actool "github.com/Autumn-27/norma/tool"
|
||||
)
|
||||
|
||||
func toolResultText(res actool.Result) string {
|
||||
var parts []string
|
||||
for _, b := range res.Content {
|
||||
if b.Text != "" {
|
||||
parts = append(parts, b.Text)
|
||||
}
|
||||
}
|
||||
return strings.Join(parts, "\n")
|
||||
}
|
||||
|
||||
func TestResumeTaskToolReopensDoneTaskWithOpenIntents(t *testing.T) {
|
||||
m, err := NewManager(t.TempDir(), "")
|
||||
if err != nil {
|
||||
t.Skipf("postgres unavailable (%v) - skipping", err)
|
||||
}
|
||||
defer m.Close()
|
||||
|
||||
task, err := m.CreateTask("reopen done task", "finish open intents", nil, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _, _ = m.DeleteTask(task.ID, DeleteTaskOptions{}) }()
|
||||
|
||||
goalID, err := task.Store.AddGoal(map[string]any{"text": "initial goal"}, "system")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := task.Store.SetNodeState(goalID, "met"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
intentID, err := task.Store.AddIntent(map[string]any{"summary": "test /admin endpoint"}, 8, nil, "planner")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := m.SetTaskStatus(task.ID, "done"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
s := newAdmissionTestServer(m, nil)
|
||||
in, _ := json.Marshal(map[string]any{"task_id": task.ID})
|
||||
res, err := s.toolResumeTask().Call(context.Background(), in, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if res.IsError {
|
||||
t.Fatalf("resume_task failed: %s", toolResultText(res))
|
||||
}
|
||||
var out struct {
|
||||
TaskID string `json:"task_id"`
|
||||
Status string `json:"status"`
|
||||
Queued bool `json:"queued"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(toolResultText(res)), &out); err != nil {
|
||||
t.Fatalf("unmarshal result %q: %v", toolResultText(res), err)
|
||||
}
|
||||
if out.TaskID != task.ID || out.Status != "running" || out.Queued {
|
||||
t.Fatalf("resume_task result = %+v, want task_id=%s status=running queued=false", out, task.ID)
|
||||
}
|
||||
if got := m.TaskStatus(task.ID); got != "running" {
|
||||
t.Fatalf("in-memory task status = %q, want running", got)
|
||||
}
|
||||
stored, err := m.pg.GetTask(mustTaskID(t, task.ID))
|
||||
if err != nil || stored == nil {
|
||||
t.Fatalf("GetTask: %v", err)
|
||||
}
|
||||
if stored.Status != "running" || stored.Paused || stored.CompletedAt != nil {
|
||||
t.Fatalf("stored task = %+v, want status=running paused=false completed_at=nil", stored)
|
||||
}
|
||||
// Existing open intent must still be present in place.
|
||||
node, err := task.Store.GetNode(intentID)
|
||||
if err != nil || node == nil || node.State != "open" {
|
||||
t.Fatalf("open intent after reopen = %+v err=%v, want state=open", node, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResumeTaskToolRefusesDoneTaskWithNoOpenWork(t *testing.T) {
|
||||
m, err := NewManager(t.TempDir(), "")
|
||||
if err != nil {
|
||||
t.Skipf("postgres unavailable (%v) - skipping", err)
|
||||
}
|
||||
defer m.Close()
|
||||
|
||||
task, err := m.CreateTask("done no work", "all goals met", nil, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _, _ = m.DeleteTask(task.ID, DeleteTaskOptions{}) }()
|
||||
|
||||
goalID, err := task.Store.AddGoal(map[string]any{"text": "finished goal"}, "system")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := task.Store.SetNodeState(goalID, "met"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := m.SetTaskStatus(task.ID, "done"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
s := newAdmissionTestServer(m, nil)
|
||||
in, _ := json.Marshal(map[string]any{"task_id": task.ID})
|
||||
res, err := s.toolResumeTask().Call(context.Background(), in, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !res.IsError {
|
||||
t.Fatalf("expected error for done task with no open goals/intents, got: %s", toolResultText(res))
|
||||
}
|
||||
if got := m.TaskStatus(task.ID); got != "done" {
|
||||
t.Fatalf("status changed to %q on refused reopen, want done", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResumeTaskToolInMainAgentContextDefaultsAndScopesTaskID(t *testing.T) {
|
||||
m, err := NewManager(t.TempDir(), "")
|
||||
if err != nil {
|
||||
t.Skipf("postgres unavailable (%v) - skipping", err)
|
||||
}
|
||||
defer m.Close()
|
||||
|
||||
task1, err := m.CreateTask("task1", "goal1", nil, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _, _ = m.DeleteTask(task1.ID, DeleteTaskOptions{}) }()
|
||||
task2, err := m.CreateTask("task2", "goal2", nil, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _, _ = m.DeleteTask(task2.ID, DeleteTaskOptions{}) }()
|
||||
|
||||
if _, err := task1.Store.AddIntent(map[string]any{"summary": "open work 1"}, 5, nil, "planner"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := task2.Store.AddIntent(map[string]any{"summary": "open work 2"}, 5, nil, "planner"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := m.SetTaskStatus(task1.ID, "done"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := m.SetTaskStatus(task2.ID, "done"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
s := newAdmissionTestServer(m, nil)
|
||||
ctx := agent.WithRunInfo(context.Background(), agent.RunInfo{TaskID: mustTaskID(t, task1.ID)})
|
||||
|
||||
// Cross-task call from task1 context must be refused.
|
||||
crossIn, _ := json.Marshal(map[string]any{"task_id": task2.ID})
|
||||
crossRes, err := s.toolResumeTask().Call(ctx, crossIn, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !crossRes.IsError {
|
||||
t.Fatalf("expected cross-task resume refusal, got: %s", toolResultText(crossRes))
|
||||
}
|
||||
if m.TaskStatus(task2.ID) != "done" {
|
||||
t.Fatalf("task2 status = %q, want done", m.TaskStatus(task2.ID))
|
||||
}
|
||||
|
||||
// Empty task_id in task1 context defaults to task1 and reopens it.
|
||||
selfRes, err := s.toolResumeTask().Call(ctx, json.RawMessage(`{}`), nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if selfRes.IsError {
|
||||
t.Fatalf("in-task resume_task failed: %s", toolResultText(selfRes))
|
||||
}
|
||||
if m.TaskStatus(task1.ID) != "running" {
|
||||
t.Fatalf("task1 status = %q, want running", m.TaskStatus(task1.ID))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetTaskGoalsAndAddTaskIntentReviveDoneAndPausedTasks(t *testing.T) {
|
||||
m, err := NewManager(t.TempDir(), "")
|
||||
if err != nil {
|
||||
t.Skipf("postgres unavailable (%v) - skipping", err)
|
||||
}
|
||||
defer m.Close()
|
||||
|
||||
s := newAdmissionTestServer(m, nil)
|
||||
|
||||
// 1. set_task_goals on a done task (no open goals/intents) writes an open goal and revives it.
|
||||
doneTask, err := m.CreateTask("done for set_task_goals", "old goal", nil, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _, _ = m.DeleteTask(doneTask.ID, DeleteTaskOptions{}) }()
|
||||
gID, err := doneTask.Store.AddGoal(map[string]any{"text": "old goal"}, "system")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := doneTask.Store.SetNodeState(gID, "met"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := m.SetTaskStatus(doneTask.ID, "done"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
inGoals, _ := json.Marshal(map[string]any{
|
||||
"task_id": doneTask.ID,
|
||||
"text": "verify SSRF on /api/fetch",
|
||||
})
|
||||
res, err := s.toolSetTaskGoals().Call(context.Background(), inGoals, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if res.IsError {
|
||||
t.Fatalf("set_task_goals failed: %s", toolResultText(res))
|
||||
}
|
||||
if got := m.TaskStatus(doneTask.ID); got != "running" {
|
||||
t.Fatalf("doneTask status after set_task_goals = %q, want running", got)
|
||||
}
|
||||
hasOpenGoal, err := doneTask.Store.HasOpenGoal()
|
||||
if err != nil || !hasOpenGoal {
|
||||
t.Fatalf("doneTask HasOpenGoal = %v err=%v, want true", hasOpenGoal, err)
|
||||
}
|
||||
|
||||
// 2. set_task_goals on a paused task clears pause and revives it.
|
||||
if _, err := s.applyTaskControl(doneTask, "pause"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !doneTask.lifecycleSnapshot().Paused {
|
||||
t.Fatal("expected task to be paused")
|
||||
}
|
||||
inGoals2, _ := json.Marshal(map[string]any{
|
||||
"task_id": doneTask.ID,
|
||||
"goals": []map[string]any{{"text": "check IDOR on /api/users/{id}", "vulnclass": "IDOR"}},
|
||||
})
|
||||
res, err = s.toolSetTaskGoals().Call(context.Background(), inGoals2, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if res.IsError {
|
||||
t.Fatalf("set_task_goals on paused task failed: %s", toolResultText(res))
|
||||
}
|
||||
if doneTask.lifecycleSnapshot().Paused || s.engine.IsPaused(doneTask.ID) {
|
||||
t.Fatalf("task still paused after set_task_goals: lifecycle=%+v enginePaused=%v", doneTask.lifecycleSnapshot(), s.engine.IsPaused(doneTask.ID))
|
||||
}
|
||||
|
||||
// 3. add_task_intent on a done task creates an open intent and revives it.
|
||||
intentTask, err := m.CreateTask("done for add_task_intent", "old goal", nil, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _, _ = m.DeleteTask(intentTask.ID, DeleteTaskOptions{}) }()
|
||||
gID2, err := intentTask.Store.AddGoal(map[string]any{"text": "old goal"}, "system")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := intentTask.Store.SetNodeState(gID2, "met"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := m.SetTaskStatus(intentTask.ID, "done"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
inIntent, _ := json.Marshal(map[string]any{
|
||||
"task_id": intentTask.ID,
|
||||
"summary": "probe /internal/metrics directly",
|
||||
"priority": 9,
|
||||
})
|
||||
res, err = s.toolAddTaskIntent().Call(context.Background(), inIntent, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if res.IsError {
|
||||
t.Fatalf("add_task_intent failed: %s", toolResultText(res))
|
||||
}
|
||||
if got := m.TaskStatus(intentTask.ID); got != "running" {
|
||||
t.Fatalf("intentTask status after add_task_intent = %q, want running", got)
|
||||
}
|
||||
hasActive, err := intentTask.Store.HasActiveIntent()
|
||||
if err != nil || !hasActive {
|
||||
t.Fatalf("intentTask HasActiveIntent = %v err=%v, want true", hasActive, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPResumeTaskEndpoint(t *testing.T) {
|
||||
m, err := NewManager(t.TempDir(), "")
|
||||
if err != nil {
|
||||
t.Skipf("postgres unavailable (%v) - skipping", err)
|
||||
}
|
||||
defer m.Close()
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
td := t.TempDir()
|
||||
s := New(ctx, m, td, td, td)
|
||||
planner, worker := new(agent.Planner), new(agent.Worker)
|
||||
s.engine.SetAuthoritativeAgentResolver(func(*Task) (*agent.Planner, *agent.Worker) {
|
||||
return planner, worker
|
||||
})
|
||||
h := s.Handler()
|
||||
token, err := signJWT(s.jwtKey)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
postResume := func(id string) *httptest.ResponseRecorder {
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/tasks/"+id+"/resume", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
||||
// Missing task → 404.
|
||||
if rec := postResume("999999999"); rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("missing task status = %d body=%s, want 404", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
task, err := m.CreateTask("http resume", "goal", nil, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _, _ = m.DeleteTask(task.ID, DeleteTaskOptions{}) }()
|
||||
goalID, err := task.Store.AddGoal(map[string]any{"text": "g"}, "system")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := task.Store.SetNodeState(goalID, "met"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := m.SetTaskStatus(task.ID, "done"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Done task with no open goals/intents → 409.
|
||||
if rec := postResume(task.ID); rec.Code != http.StatusConflict {
|
||||
t.Fatalf("done task with no work status = %d body=%s, want 409", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
// Add an open intent → POST /api/tasks/{id}/resume reopens to 200 running.
|
||||
if _, err := task.Store.AddIntent(map[string]any{"summary": "continue open work"}, 7, nil, "planner"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec := postResume(task.ID)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("reopen done task status = %d body=%s, want 200", rec.Code, rec.Body.String())
|
||||
}
|
||||
var body taskControlResult
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if body.ID != task.ID || body.Status != "running" || body.Paused {
|
||||
t.Fatalf("resume body = %+v, want id=%s status=running paused=false", body, task.ID)
|
||||
}
|
||||
|
||||
// Already running → 409.
|
||||
if rec := postResume(task.ID); rec.Code != http.StatusConflict {
|
||||
t.Fatalf("already running status = %d body=%s, want 409", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
// Pause then resume → 200 running.
|
||||
if _, err := s.applyTaskControl(task, "pause"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if rec := postResume(task.ID); rec.Code != http.StatusOK {
|
||||
t.Fatalf("resume paused task status = %d body=%s, want 200", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutoAndMainAgentToolResolutionIncludesReopenTools(t *testing.T) {
|
||||
m, err := NewManager(t.TempDir(), "")
|
||||
if err != nil {
|
||||
t.Skipf("postgres unavailable (%v) - skipping", err)
|
||||
}
|
||||
defer m.Close()
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
td := t.TempDir()
|
||||
s := New(ctx, m, td, td, td)
|
||||
t.Cleanup(func() { agent.ToolResolve = nil })
|
||||
|
||||
// Verify auto gets resume_task, set_task_goals, add_task_intent via ToolResolve.
|
||||
hostTools, _ := s.hostTools()
|
||||
autoTools := names(agent.ToolResolve(context.Background(), "auto", append(actool.DefaultTools(), hostTools...)))
|
||||
for _, want := range []string{"resume_task", "set_task_goals", "add_task_intent", "pause_task", "add_task_hint"} {
|
||||
if _, ok := autoTools[want]; !ok {
|
||||
t.Errorf("auto missing bound tool %q", want)
|
||||
}
|
||||
}
|
||||
|
||||
// Verify mainagent gets resume_task alongside set_goals and add_intent.
|
||||
ts := agent.NewToolSet(nil, "human")
|
||||
mainBase := append(ts.MainAgentTools(), hostTools...)
|
||||
mainTools := names(agent.ToolResolve(context.Background(), "mainagent", mainBase))
|
||||
for _, want := range []string{"resume_task", "set_goals", "add_intent", "add_hint"} {
|
||||
if _, ok := mainTools[want]; !ok {
|
||||
t.Errorf("mainagent missing bound tool %q", want)
|
||||
}
|
||||
}
|
||||
// Verify cross-task-only tools are NOT leaked into mainagent.
|
||||
for _, unwanted := range []string{"set_task_goals", "add_task_intent"} {
|
||||
if _, ok := mainTools[unwanted]; ok {
|
||||
t.Errorf("mainagent should not receive cross-task tool %q", unwanted)
|
||||
}
|
||||
}
|
||||
|
||||
// Verify MCP resume_task can also reopen a done task with open intents.
|
||||
task, err := m.CreateTask("mcp reopen", "goal", nil, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _, _ = m.DeleteTask(task.ID, DeleteTaskOptions{}) }()
|
||||
if _, err := task.Store.AddIntent(map[string]any{"summary": "remaining intent"}, 6, nil, "planner"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := m.SetTaskStatus(task.ID, "done"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tok := &db.APIToken{ID: 1, Name: "test", Scopes: []string{db.APIScopeTaskControl}}
|
||||
mcpIn, _ := json.Marshal(map[string]any{"task_id": task.ID})
|
||||
mcpRes, err := s.mcpControlTask(tok, mcpIn, "resume")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if mcpRes.IsError || !strings.Contains(toolResultText(mcpRes), `"running"`) {
|
||||
t.Fatalf("mcp resume_task on done task = %+v, want running", mcpRes)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user