From c203af2f5caff9f015566e33a30b3bbf35f3f4b6 Mon Sep 17 00:00:00 2001 From: BaaRai <130491490+BaaRai@users.noreply.github.com> Date: Thu, 26 Nov 2026 21:35:20 +0100 Subject: [PATCH] fix(agent): keep Auto and MainAgent on orchestration tools, not Bash/WebFetch Fixes #544 --- agent/chat.go | 63 ++++++-- agent/hooks_reach_test.go | 12 +- agent/mainagent.go | 22 ++- agent/noise_profile_test.go | 18 ++- agent/orchestrator_tools_test.go | 246 ++++++++++++++++++++++++++++++ agent/promptcatalog.go | 25 +-- agent/toolcatalog.go | 21 +-- agent/tools.go | 4 + agent/webfetch_dialer_test.go | 15 +- agent/webfetch_redirect_test.go | 19 +-- db/db.go | 9 +- db/skill_visibility_test.go | 2 +- server/assembly.go | 81 +++++----- server/orchestration.go | 94 +++++++++++- server/orchestrator_tools_test.go | 202 ++++++++++++++++++++++++ server/server.go | 2 +- server/target_gate_scope_test.go | 32 ++-- 17 files changed, 734 insertions(+), 133 deletions(-) create mode 100644 agent/orchestrator_tools_test.go create mode 100644 server/orchestrator_tools_test.go diff --git a/agent/chat.go b/agent/chat.go index c4acbc8f..82bc4b6b 100644 --- a/agent/chat.go +++ b/agent/chat.go @@ -20,9 +20,11 @@ import ( // ChatAgent is the generic, task-independent conversational runner behind the chat // page. It generalizes MainAgent.Chat: any agent (built-in OR a custom one, by -// key) can be chatted with, multi-turn history resumed from the transcript. It is -// a PURE ASSISTANT — base tools are the SDK DefaultTools (Bash/Read/Write/Edit/ -// LS/Glob/Grep) plus whatever skills/MCP the key is made visible; NO pentest +// key) can be chatted with, multi-turn history resumed from the transcript. +// Execution chat agents (solo pentest, custom assistants) start with the SDK +// DefaultTools (Bash/Read/Write/Edit/LS/Glob/Grep) plus WebFetch and visible +// skills/MCP. Orchestration chat agents (auto) get no DefaultTools and no +// WebFetch — only their bound orchestration/platform/domain tools. NO pentest // graph/task context is injected (that stays exclusive to MainAgent). type ChatAgent struct { prov llm.Provider @@ -83,17 +85,48 @@ func chatWorkDirSpec(workDir string) string { return "\n\n**File output rules**: whenever you need to write a file, write it to the working directory " + workDir + " (this is the default CWD — relative paths land here, and you may also use this absolute path) — do not write to /tmp or other absolute paths." } +// isOrchestrationChatAgent reports whether a chat agent key is a pure +// orchestrator that dispatches work through platform/task tools instead of +// running shell, file, or HTTP tools itself. +func isOrchestrationChatAgent(agentKey string) bool { + return agentKey == "auto" +} + // chatSystem renders the DB-managed prompt body for agentKey. Custom agents have // no per-key in-code default, so DefaultAssistantPrompt is the render fallback. -// Every chat agent, built-in or custom, can read target-derived content through -// WebFetch or Bash, so all of them get the code-owned untrusted-content tail -// after the editable body. +// Every chat agent, built-in or custom, can read target-derived content (via +// WebFetch/Bash or task traces/findings), so all of them get the code-owned +// untrusted-content tail after the editable body. Execution chat agents also get +// the session working-directory notice and active noise profile guidance. func chatSystem(agentKey, dataDir, workDir string) string { body := renderSystem(agentKey, DefaultAssistantPrompt, chatVars{DataDir: dataDir, Now: nowStr()}) body += untrustedContentTail(body) + if isOrchestrationChatAgent(agentKey) { + return body + } return body + chatWorkDirSpec(workDir) + noiseProfileBlock() } +// chatBaseTools returns the built-in base tool set for a chat agent before +// AugmentTools runs. Orchestration agents (auto) get no SDK DefaultTools so they +// dispatch via platform/task tools instead of executing commands themselves. +func chatBaseTools(agentKey, workDir string) []actool.CoreTool { + if isOrchestrationChatAgent(agentKey) { + return nil + } + return defaultTools(workDir) // file tools confined to sessionWorkDir (filetools.go) +} + +// assembleChatTools builds the final tool list for a chat agent run. +func assembleChatTools(ctx context.Context, agentKey, workDir, proxyAddr, proxyCACert string) ([]actool.CoreTool, DeferredInfo, func()) { + base := chatBaseTools(agentKey, workDir) + tools, def, cleanup := AugmentTools(ctx, agentKey, base) + if !isOrchestrationChatAgent(agentKey) { + tools = withWebFetch(ctx, tools, proxyAddr, proxyCACert) // WebFetch: routed through the recording proxy for tracing; loads the proxy CA to verify MITM-resigned HTTPS certificates; every redirect hop is gated + } + return tools, def, cleanup +} + // chatVars carries the runtime variables a custom agent's prompt may reference. // DataDir (server data root) + Now (server wall-clock, refreshed each turn) are the // universal ones; any other {{.X}} fails to render and falls back to @@ -156,20 +189,24 @@ func (c *ChatAgent) Chat(ctx context.Context, agentKey, sessionID, message strin makeRunDir(c.workDir, sessionWorkDir) ctx = intercept.WithReviewWorkingDirectory(ctx, sessionWorkDir) - // 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 := defaultTools(c.workDir) // file tools confined to sessionWorkDir (filetools.go) + // Execution chat agents start with DefaultTools + WebFetch; orchestration + // agents (auto) receive only the orchestration/domain tools wired by + // AugmentTools / ToolResolve. ctx = WithRunInfo(ctx, RunInfo{SessionID: sessionID}) - tools, def, cleanup := AugmentTools(ctx, agentKey, base) + tools, def, cleanup := assembleChatTools(ctx, agentKey, c.workDir, c.proxyAddr, c.proxyCACert) defer cleanup() + var bashEnv []string + if !isOrchestrationChatAgent(agentKey) { + bashEnv = proxyEnv(c.proxyAddr, c.proxyCACert) // Bash subcommands go through the proxy + trust the CA by default + } + system, boundary := deferredSystem(chatSystem(agentKey, c.workDir, sessionWorkDir), def) opts := agentcore.Options{ Provider: c.prov, SystemPrompt: system, DynamicBoundary: boundary, - Tools: withWebFetch(ctx, tools, c.proxyAddr, c.proxyCACert), // WebFetch: routed through the recording proxy for tracing; loads the proxy CA to verify MITM-resigned HTTPS certificates; every redirect hop is gated + Tools: tools, DeferredTools: def.Deferred, UnlockSet: def.Unlock, PermissionMode: permission.ModeBypass, @@ -185,7 +222,7 @@ func (c *ChatAgent) Chat(ctx context.Context, agentKey, sessionID, message strin DeepSeekSearchAPIKey: ws.DeepSeekAPIKey, DeepSeekSearchModel: ws.DeepSeekModel, WebSearchProxy: ws.Proxy, - BashEnv: proxyEnv(c.proxyAddr, c.proxyCACert), // Bash subcommands go through the proxy + trust the CA by default + BashEnv: bashEnv, WorkingDir: sessionWorkDir, MaxTurns: maxTurns, MaxDuration: maxDuration, diff --git a/agent/hooks_reach_test.go b/agent/hooks_reach_test.go index efaaf2e0..37af6478 100644 --- a/agent/hooks_reach_test.go +++ b/agent/hooks_reach_test.go @@ -139,12 +139,16 @@ func TestPlannerToolCallReachesHooks(t *testing.T) { func TestMainAgentToolCallReachesHooks(t *testing.T) { f := newHookReachFixture(t) hooks := &recordingHooks{} - main := NewMainAgent(toolCallThenStop("Bash", f.bash), "test-model", f.workDir, nil, 0, 3) - if _, err := main.Chat(f.ctx, f.expID, 0, nil, f.ts, "probe goal", "status?", hooks, nil, nil, nil, nil, nil); err != nil { + main := NewMainAgent(toolCallThenStop("add_hint", `{"text":"focus on auth"}`), "test-model", f.workDir, nil, 0, 3) + if _, err := main.Chat(f.ctx, f.expID, 0, nil, f.ts, "probe goal", "focus on auth", hooks, nil, nil, nil, nil, nil); err != nil { t.Fatal(err) } - hooks.assertOneScopedCall(t, "Bash", f.taskID) - f.assertToolDidNotRun(t) + hooks.assertOneScopedCall(t, "add_hint", f.taskID) + if hints, err := f.ts.ListByKind("hint", 10); err != nil { + t.Fatal(err) + } else if len(hints) != 0 { + t.Fatalf("blocked add_hint still wrote %d hint node(s)", len(hints)) + } } func TestWorkerToolCallReachesHooks(t *testing.T) { diff --git a/agent/mainagent.go b/agent/mainagent.go index 834f1004..0742bd5e 100644 --- a/agent/mainagent.go +++ b/agent/mainagent.go @@ -88,11 +88,10 @@ func (m *MainAgent) SetWebSearch(o WebSearchOpts) { m.webSearch = o } func (m *MainAgent) SetSteerWork(fn func(intentID int64, msg string) error) { m.steerWork = fn } // mainAgentDefaultTmpl is the built-in EDITABLE body (section [A]) of the main agent -// prompt, seeded into agent_prompts. Goal is a {{.Goal}} template var; the -// intermediate-artifact output rules tail is code-owned (artifactSpec), appended after rendering. -const mainAgentDefaultTmpl = `You are the "main agent" of an authorized penetration-testing system, the interface to the human operator. You do not explore in person, nor do you autonomously generate intents in a loop (that is the planner's job). Your duties: +// prompt, seeded into agent_prompts. Goal is a {{.Goal}} template var. +const mainAgentDefaultTmpl = `You are the "main agent" of an authorized penetration-testing system, the interface to the human operator. You are an orchestrator only: you have no shell, file, or direct HTTP tools, you never probe or exploit targets in person, and you do not autonomously generate intents in a loop (that is the planner's job). Your duties: -1. Observe: use graph_overview / list_findings / list_facts / list_assets / get_worker_output to answer the human's questions about current progress. +1. Observe: use graph_overview / list_findings / list_facts / list_assets / get_worker_output / get_worker_trace / search_all_worker_traces / node_detail to answer the human's questions about current progress. 2. Steer (land the human's intent into the system): - The human wants to "change direction / emphasize a vulnerability class / focus an area" → write a hint with add_hint (the planner will read it next round). - The human wants to "test a specific target right now" → inject one high-priority intent directly with add_intent (priority 8-10). The system automatically pulls a completed task back to running so a worker claims and executes this intent, returning to completed when done. @@ -106,9 +105,9 @@ Current task goal: {{.Goal}} Do not fabricate findings; answer only from real data returned by tools.` -func mainAgentSystem(goal, dataDir, workDir string) string { +func mainAgentSystem(goal, dataDir, _ string) string { body := renderSystem("mainagent", mainAgentDefaultTmpl, MainVars{Goal: goal, DataDir: dataDir, Now: nowStr()}) - return body + untrustedContentTail(body) + artifactSpec(workDir) + noiseProfileBlock() + return body + untrustedContentTail(body) } // Chat handles one human message and returns the assistant reply. emit, if @@ -130,9 +129,9 @@ func (m *MainAgent) Chat(ctx context.Context, taskID int64, mainSeg int, as *db. tsx.SetNotifyGoal(notifyGoal) // set_goals adds a goal → record a "human added a goal: …" trigger for the planner tsx.SetNotifyHint(notifyHint) // add_hint adds hints → record a "human added N strategic hints: …" trigger for the planner (origin "human") tsx.steerWork = m.steerWork // enable steer_work tool (nil = unavailable) - // domain tools + basic default toolset (Read/Write/Edit/MultiEdit/LS/Glob/Grep/Bash) - // when the asset coverage feature is off, drop add_task_scope/list_untested_assets (not in the prompt). - base := append(tsx.DropCoverageTools(tsx.MainAgentTools()), defaultTools(m.workDir)...) + // Orchestration domain tools only (no SDK DefaultTools, no WebFetch). + // When the asset coverage feature is off, drop add_task_scope/list_untested_assets (not in the prompt). + base := tsx.DropCoverageTools(tsx.MainAgentTools()) ctx = WithRunInfo(ctx, RunInfo{TaskID: taskID, ExplorationID: explorationID(ts)}) tools, def, cleanup := AugmentTools(ctx, "mainagent", base) defer cleanup() @@ -144,7 +143,7 @@ func (m *MainAgent) Chat(ctx context.Context, taskID int64, mainSeg int, as *db. Provider: m.prov, SystemPrompt: system, DynamicBoundary: boundary, - Tools: withWebFetch(ctx, tools, m.proxyAddr, m.proxyCACert), // WebFetch: routed through the recording proxy for tracing; loads the proxy CA to verify MITM-resigned HTTPS certificates; every redirect hop is gated + Tools: tools, DeferredTools: def.Deferred, UnlockSet: def.Unlock, PermissionMode: permission.ModeBypass, @@ -160,8 +159,7 @@ func (m *MainAgent) Chat(ctx context.Context, taskID int64, mainSeg int, as *db. DeepSeekSearchAPIKey: m.webSearch.DeepSeekAPIKey, DeepSeekSearchModel: m.webSearch.DeepSeekModel, WebSearchProxy: m.webSearch.Proxy, - BashEnv: proxyEnv(m.proxyAddr, m.proxyCACert), // Bash subcommands go through the proxy + trust the CA by default - WorkingDir: mainDir, // the main run directory /tasks//main + WorkingDir: mainDir, // the main run directory /tasks//main ToolOutputDir: TaskToolOutputDir(m.workDir, taskID, mainDir), MaxTurns: m.maxTurns, // 0 = unlimited (configurable in agent management) Compaction: compactionConfig(m.compactionWindow()), // long chats stay within the window diff --git a/agent/noise_profile_test.go b/agent/noise_profile_test.go index d24490a5..db3e45ba 100644 --- a/agent/noise_profile_test.go +++ b/agent/noise_profile_test.go @@ -51,13 +51,18 @@ func TestRenderNoiseProfileTable(t *testing.T) { } // The default must stay identical: with no profile the block is empty and none of -// the four prompts that can launch Bash gains any text. +// the prompts that can launch Bash gains any text. Pure orchestration prompts +// (mainagent, auto) have no Bash/WebFetch and omit the scanner noise block. func TestPromptBuildersNoiseBlock(t *testing.T) { builders := map[string]func() string{ - "planner": func() string { return plannerSystem("goal", "/data", "/work") }, - "worker": func() string { return workerSystem("", "", "/data", "/run") }, + "planner": func() string { return plannerSystem("goal", "/data", "/work") }, + "worker": func() string { return workerSystem("", "", "/data", "/run") }, + "pentest": func() string { return chatSystem("pentest", "/data", "/work") }, + "chat": func() string { return chatSystem("assistant", "/data", "/work") }, + } + orchestrators := map[string]func() string{ "mainagent": func() string { return mainAgentSystem("goal", "/data", "/work") }, - "chat": func() string { return chatSystem("auto", "/data", "/work") }, + "auto": func() string { return chatSystem("auto", "/data", "/work") }, } prev := egress.CurrentProfile() t.Cleanup(func() { egress.SetProfile(prev) }) @@ -77,5 +82,10 @@ func TestPromptBuildersNoiseBlock(t *testing.T) { t.Errorf("%s after SetProfile(%s) is missing its block or shows the env profile", name, profile) } } + for name, build := range orchestrators { + if got := build(); strings.Contains(got, noiseProfileHeader) { + t.Errorf("orchestrator %s after SetProfile(%s) should not receive scanner noise block", name, profile) + } + } } } diff --git a/agent/orchestrator_tools_test.go b/agent/orchestrator_tools_test.go new file mode 100644 index 00000000..a04ca062 --- /dev/null +++ b/agent/orchestrator_tools_test.go @@ -0,0 +1,246 @@ +package agent + +import ( + "context" + "encoding/json" + "iter" + "slices" + "strings" + "sync" + "testing" + + "github.com/Autumn-27/artex/db" + "github.com/Autumn-27/norma/llm" + actool "github.com/Autumn-27/norma/tool" +) + +// captureToolNamesProvider records the tool names offered to the model on its +// first completion/stream request and ends the turn immediately. +type captureToolNamesProvider struct { + mu sync.Mutex + names []string +} + +func (p *captureToolNamesProvider) record(req llm.CompletionRequest) { + p.mu.Lock() + defer p.mu.Unlock() + if p.names != nil { + return + } + p.names = make([]string, 0, len(req.Tools)) + for _, t := range req.Tools { + p.names = append(p.names, t.Name) + } +} + +func (p *captureToolNamesProvider) seen() map[string]bool { + p.mu.Lock() + defer p.mu.Unlock() + out := make(map[string]bool, len(p.names)) + for _, n := range p.names { + out[n] = true + } + return out +} + +func (p *captureToolNamesProvider) Complete(_ context.Context, req llm.CompletionRequest) (llm.Message, string, llm.Usage, error) { + p.record(req) + return llm.Message{Role: llm.RoleAssistant, Content: []llm.ContentBlock{llm.TextBlock("ok")}}, "end_turn", llm.Usage{}, nil +} + +func (p *captureToolNamesProvider) Stream(_ context.Context, req llm.CompletionRequest) iter.Seq2[llm.StreamEvent, error] { + p.record(req) + return func(yield func(llm.StreamEvent, error) bool) { + yield(llm.StreamEvent{Type: llm.SETextDelta, Text: "ok"}, nil) + yield(llm.StreamEvent{Type: llm.SEMessageDelta, StopReason: "end_turn"}, nil) + } +} + +func dummyTool(name string) actool.CoreTool { + return readTool(name, "test fixture "+name, obj(map[string]any{}), func(context.Context, json.RawMessage) (actool.Result, error) { + return actool.Text("ok"), nil + }) +} + +func toolNameSet(tools []actool.CoreTool) map[string]bool { + out := make(map[string]bool, len(tools)) + for _, t := range tools { + out[t.Name()] = true + } + return out +} + +// TestOrchestratorAgentsExcludeExecutionTools pins issue #544: +// - auto receives only its orchestration/domain tools (no DefaultTools, no WebFetch, no Skill); +// - mainagent receives MainAgentTools only (no DefaultTools, no WebFetch); +// - solo pentest, custom chat assistants, and workers keep Bash and WebFetch. +func TestOrchestratorAgentsExcludeExecutionTools(t *testing.T) { + oldAug, oldRes := ToolAugment(), ToolResolve() + t.Cleanup(func() { + SetToolAugment(oldAug) + SetToolResolve(oldRes) + }) + SetToolResolve(nil) + SetToolAugment(func(_ context.Context, agentKey string) ([]actool.CoreTool, DeferredInfo, func()) { + if agentKey == "auto" { + return []actool.CoreTool{ + dummyTool("spawn_task"), + dummyTool("add_task_hint"), + dummyTool("set_goals"), + dummyTool("set_constraints"), + dummyTool("list_tasks"), + }, DeferredInfo{}, func() {} + } + return nil, DeferredInfo{}, func() {} + }) + + workDir := t.TempDir() + forbiddenForOrchestrators := []string{"Bash", "Read", "Write", "Edit", "MultiEdit", "LS", "Glob", "Grep", "WebFetch", "Skill"} + + t.Run("auto chat gets orchestration tools only", func(t *testing.T) { + prov := &captureToolNamesProvider{} + c := NewChatAgent(prov, "test-model", workDir, nil, 100000) + if _, err := c.Chat(t.Context(), "auto", "conv-auto-544", "recon https://example.com", 1, 0, false, nil); err != nil { + t.Fatal(err) + } + got := prov.seen() + for _, want := range []string{"spawn_task", "add_task_hint", "set_goals", "set_constraints", "list_tasks"} { + if !got[want] { + t.Errorf("auto missing orchestration tool %q (got: %v)", want, got) + } + } + for _, bad := range forbiddenForOrchestrators { + if got[bad] { + t.Errorf("auto must not have execution tool %q", bad) + } + } + }) + + t.Run("pentest solo chat keeps Bash and WebFetch", func(t *testing.T) { + prov := &captureToolNamesProvider{} + c := NewChatAgent(prov, "test-model", workDir, nil, 100000) + if _, err := c.Chat(t.Context(), "pentest", "conv-pentest-544", "hello", 1, 0, false, nil); err != nil { + t.Fatal(err) + } + got := prov.seen() + for _, want := range []string{"Bash", "Read", "Write", "Edit", "WebFetch"} { + if !got[want] { + t.Errorf("pentest missing expected tool %q", want) + } + } + }) + + t.Run("custom chat agent keeps Bash and WebFetch", func(t *testing.T) { + prov := &captureToolNamesProvider{} + c := NewChatAgent(prov, "test-model", workDir, nil, 100000) + if _, err := c.Chat(t.Context(), "custom-helper", "conv-custom-544", "hello", 1, 0, false, nil); err != nil { + t.Fatal(err) + } + got := prov.seen() + for _, want := range []string{"Bash", "WebFetch"} { + if !got[want] { + t.Errorf("custom chat agent missing expected tool %q", want) + } + } + }) + + t.Run("mainagent has MainAgentTools and no Bash/Write/Edit/WebFetch", func(t *testing.T) { + ts := NewToolSet(nil, "human") + tools, _, cleanup := AugmentTools(t.Context(), "mainagent", ts.DropCoverageTools(ts.MainAgentTools())) + defer cleanup() + got := toolNameSet(tools) + for _, want := range []string{"graph_overview", "add_hint", "add_intent", "steer_work", "set_goals", "set_constraints", "list_findings"} { + if !got[want] { + t.Errorf("mainagent missing domain tool %q", want) + } + } + for _, bad := range forbiddenForOrchestrators { + if got[bad] { + t.Errorf("mainagent must not have execution tool %q", bad) + } + } + }) + + t.Run("mainagent live chat advertises no Bash/Write/Edit/WebFetch", func(t *testing.T) { + d := testDB(t) + t.Cleanup(func() { _ = d.Close() }) + expID, err := d.CreateExploration("mainagent tools", "verify orchestration-only") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _, _ = d.Exec(`DELETE FROM explorations WHERE id=$1`, expID) }) + prov := &captureToolNamesProvider{} + m := NewMainAgent(prov, "test-model", workDir, nil, 0, 1) + if _, err := m.Chat(t.Context(), expID, 0, nil, d.Exploration(expID), "verify goal", "status?", nil, nil, nil, nil, nil, nil); err != nil { + t.Fatal(err) + } + got := prov.seen() + for _, want := range []string{"graph_overview", "add_hint", "add_intent", "set_goals", "set_constraints"} { + if !got[want] { + t.Errorf("mainagent chat missing %q", want) + } + } + for _, bad := range forbiddenForOrchestrators { + if got[bad] { + t.Errorf("mainagent chat must not have %q", bad) + } + } + }) + + t.Run("worker keeps Bash and WebFetch", func(t *testing.T) { + d := testDB(t) + t.Cleanup(func() { _ = d.Close() }) + expID, err := d.CreateExploration("worker tools", "verify execution tools") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _, _ = d.Exec(`DELETE FROM explorations WHERE id=$1`, expID) }) + es := d.Exploration(expID) + payload := map[string]any{"summary": "probe"} + intentID, err := es.AddNode("intent", payload, 0, "running", "planner", nil) + if err != nil { + t.Fatal(err) + } + raw, _ := json.Marshal(payload) + prov := &captureToolNamesProvider{} + w := NewWorker(prov, "test-model", workDir, nil, 0, 1) + if _, _, err := w.Execute(t.Context(), "work#1", expID, nil, es, &db.Node{ID: intentID, Payload: raw}, nil, nil, nil, nil); err != nil { + t.Fatal(err) + } + got := prov.seen() + for _, want := range []string{"Bash", "WebFetch", "record_fact", "report_finding"} { + if !got[want] { + t.Errorf("worker missing expected tool %q", want) + } + } + }) +} + +func TestAutoBuiltinSeedsAndPromptContract(t *testing.T) { + byKey := map[string]ToolSeed{} + for _, s := range BuiltinToolSeeds() { + byKey[s.Key] = s + } + for _, key := range []string{"set_goals", "set_constraints"} { + s, ok := byKey[key] + if !ok { + t.Fatalf("missing seed %q", key) + } + if !slices.Contains(s.Agents, "auto") { + t.Errorf("%s default agents = %v, want auto included", key, s.Agents) + } + if !slices.Contains(s.Agents, "mainagent") || !slices.Contains(s.Agents, "goals") { + t.Errorf("%s lost existing default agents: %v", key, s.Agents) + } + } + + autoPrompt := BuiltinPromptSeeds()["auto"] + for _, want := range []string{"spawn_task", "seed_first_intent=true", "add_task_hint", "set_goals", "set_constraints"} { + if !strings.Contains(autoPrompt, want) { + t.Errorf("autoDefaultTmpl missing %q", want) + } + } + if strings.Contains(autoPrompt, "update_skill ") || strings.Contains(autoPrompt, "update_skill to") { + t.Errorf("autoDefaultTmpl references stale tool name update_skill instead of update_skill_file") + } +} diff --git a/agent/promptcatalog.go b/agent/promptcatalog.go index 5b54bf9f..8f7c5cc3 100644 --- a/agent/promptcatalog.go +++ b/agent/promptcatalog.go @@ -11,20 +11,25 @@ package agent // etc.), filled with runtime variables at render time. // autoDefaultTmpl is the built-in "Auto" platform-operator agent's prompt. Auto -// runs via the chat page and drives the platform through tools: task ops -// (spawn/list/pause/hint + read graph/findings/traces) and platform management -// (create/modify skill, custom tool, MCP). It seeds into agent_prompts like the -// other built-ins. -const autoDefaultTmpl = `You are **Auto**, the "operations assistant" of this penetration testing platform. You do not pentest yourself; instead you **operate the platform through tools** and get things done per the user's instructions. +// runs via the chat page and drives the platform through orchestration tools +// only (no Bash, no WebFetch, no file tools, no Skill/MCP execution): task ops +// (spawn/list/pause/hint/goals/constraints + read graph/findings/traces) and +// platform management (create/modify skill, custom tool, MCP). It seeds into +// agent_prompts like the other built-ins. +const autoDefaultTmpl = `You are **Auto**, the operations and dispatch orchestrator of this penetration testing platform. You NEVER perform reconnaissance, probing, or penetration testing yourself — you have no shell, file, or HTTP execution tools. Your job is to **dispatch work to the planner/workers and operate the platform through orchestration tools**. -What you can do (depends on which tools are enabled for you): -1. **Task operations**: list_tasks for the global view, spawn_task to start a subtask, get_task_graph / list_task_findings to read a task's progress and findings (including flags), get_task_worker_trace to see a work's execution process, pause_task to pause, add_task_hint to inject a hint into a task. -2. **Platform management**: create_skill / update_skill to create/modify skills; create_custom_tool / update_custom_tool to create/modify custom tools (command/script/http); create_mcp / update_mcp to create/modify MCP servers. +Dispatch rules (follow strictly): +1. **New target or assessment objective**: call **spawn_task** immediately with **seed_first_intent=true**, a concise description, and the concrete goal so a worker starts right away while the planner takes over. Do not try to run curl, scans, or probes yourself. +2. **Redirect / focus an existing task**: call **add_task_hint** with the task's ` + "`task_id`" + ` so the planner adjusts on its next round. +3. **Add a new final goal to an existing task**: call **set_goals** with the task's ` + "`task_id`" + ` (re-opens completed/paused tasks automatically). +4. **Add allow/deny constraints to an existing task**: call **set_constraints** with the task's ` + "`task_id`" + `. +5. **Observe and steer**: use list_tasks, get_task_graph, list_task_findings, get_task_node_detail, list_task_worker_traces, get_task_worker_trace, search_task_worker_traces, pause_task, list_assets, insert_assets, add_company_scope, and list_companies. +6. **Platform management**: use create_skill / update_skill_file, create_custom_tool / update_custom_tool, create_mcp / update_mcp, and delete_assets_by_host when asked to manage platform configuration. Principles: -- Check the current state first (list_tasks / get_task_graph etc.) before acting; get it done in one pass, no idle spinning. +- When the user gives a target and an objective, dispatch via spawn_task(seed_first_intent=true) immediately; check list_tasks first only when modifying or inspecting an existing task. - When creating/modifying a skill, tool, or MCP, translate the user's intent into correct structured parameters (kind/exec/schema etc.); when unsure about a field, fill in the minimal viable value. -- Report concisely in plain language what you did and how it turned out; answer only from real tool results, never fabricate. +- Report concisely in plain language what you dispatched or changed (including the task_id); answer only from real tool results, never fabricate. - Operate only within the authorized scope.` // pentestDefaultTmpl is the built-in "pentest" (solo penetration testing) agent's diff --git a/agent/toolcatalog.go b/agent/toolcatalog.go index 6e85c7eb..b7baa651 100644 --- a/agent/toolcatalog.go +++ b/agent/toolcatalog.go @@ -38,11 +38,13 @@ type ToolSeed struct { // Call. // // Deliberately EXCLUDES the SDK general tools actool.DefaultTools() (Read/Write/ -// Edit/MultiEdit/LS/Glob/Grep/Bash): every agent always has them, there is no -// "bind to whom" trade-off, and most of their documentation lives in Prompt() (this -// table only covers Description(), which would create misleading half-coverage). -// Not seeded → no DB row → ToolResolve passes them through untouched, behavior -// identical to before. Only artex's own domain tools enter the table as manageable. +// Edit/MultiEdit/LS/Glob/Grep/Bash): whether an agent receives them is decided +// by its role in code (execution agents — planner/worker/pentest/custom — get +// them; pure orchestration agents — auto and mainagent — do not), and most of +// their documentation lives in Prompt() (this table only covers Description(), +// which would create misleading half-coverage). Not seeded → no DB row → +// ToolResolve passes them through untouched for agents whose base includes them. +// Only artex's own domain tools enter the table as manageable. func builtinToolsByAgent() map[string][]actool.CoreTool { ts := NewToolSet(nil, "") return map[string][]actool.CoreTool{ @@ -54,10 +56,11 @@ func builtinToolsByAgent() map[string][]actool.CoreTool { // into the store. Shares the same managed tools with mainagent; the web UI can // edit description/schema and check them per agent. "goals": {ts.setGoals(), ts.setConstraints()}, - // auto binds the finding-reporting + asset-management tools by default; other - // domain tools can be checked on demand in the UI. - // New databases are seeded from here; old databases are migrated by seedAutoDefaultBindings. - "auto": {ts.addFinding(), ts.insertAssets(), ts.addCompanyScope(), ts.listAssets(), ts.listCompanies()}, + // auto binds the orchestration/goal/constraint + finding/asset tools by default; + // other domain tools can be checked on demand in the UI. + // New databases are seeded from here; old databases are migrated by seedAutoDefaultBindings + // and seedAutoGoalConstraintBindings. + "auto": {ts.addFinding(), ts.insertAssets(), ts.addCompanyScope(), ts.listAssets(), ts.listCompanies(), ts.setGoals(), ts.setConstraints()}, // pentest (solo pentest agent) binds by default: list assets / insert assets / // report finding / list findings / list companies. // New databases are seeded from here; old databases are migrated by seedPentestDefaultBindings. diff --git a/agent/tools.go b/agent/tools.go index 0aedcd70..a67aaa90 100644 --- a/agent/tools.go +++ b/agent/tools.go @@ -324,6 +324,8 @@ 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) SetGoalsTool() actool.CoreTool { return t.setGoals() } +func (t *ToolSet) SetConstraintsTool() actool.CoreTool { return t.setConstraints() } // SetEnrich wires the async enrichment engine (DNS/HTTP auto-completion). func (t *ToolSet) SetEnrich(e EnrichTrigger) { t.enrich = e } @@ -2002,6 +2004,7 @@ func (t *ToolSet) setGoals() actool.CoreTool { "★Batch preferred: put multiple goals in the goals array in a single submission; the returned ids match it in length and order (failed items get id=0, details in errors). For a single goal, omit goals and pass the top-level text.\n"+ "vulnclass is optional: the corresponding vulnerability class (e.g. SQLi/IDOR); leave empty for business-logic goals. Whether a goal is met is judged and marked met by the system; this tool only adds.", obj(map[string]any{ + "task_id": str("optional: target task id (required when called from a task-less chat agent such as Auto)"), "goals": map[string]any{"type": "array", "description": "[Prefer this] array of goals to add, processed in order. Each element: text (required, an independently verifiable final goal) + vulnclass (optional). The returned ids match this array in length and order.", "items": map[string]any{"type": "object"}}, "text": str("[single] one independently verifiable final goal"), "vulnclass": str("[single] the corresponding vulnerability class (if clear), e.g. SQLi/IDOR; may be empty for business-logic goals"), @@ -2103,6 +2106,7 @@ func (t *ToolSet) setConstraints() actool.CoreTool { "★Batch preferred: put multiple constraints in the constraints array in a single submission; the returned ids match it in length and order (failed items get id=0, details in errors). For a single constraint, omit constraints and pass the top-level text/type.\n"+ "Register only constraints [explicitly stated] in the task goal/description — don't invent any; when unsure about the type, use deny (more conservative).", obj(map[string]any{ + "task_id": str("optional: target task id (required when called from a task-less chat agent such as Auto)"), "constraints": map[string]any{"type": "array", "description": "[Prefer this] array of constraints to add, processed in order. Each element: text (required, one constraint) + type (allow|deny). The returned ids match this array in length and order.", "items": map[string]any{"type": "object"}}, "text": str("[single] the content of one operation constraint"), "type": str("[single] allow or deny; defaults to deny when omitted"), diff --git a/agent/webfetch_dialer_test.go b/agent/webfetch_dialer_test.go index e954b262..b97a0628 100644 --- a/agent/webfetch_dialer_test.go +++ b/agent/webfetch_dialer_test.go @@ -145,9 +145,10 @@ func runAgentKind(t *testing.T, kind string, f hookReachFixture, ctx context.Con if _, _, err := p.Plan(ctx, f.expID, nil, f.ts, "probe goal", nil, passHooks{}, nil); err != nil { t.Fatal(err) } - case "mainagent": - m := NewMainAgent(prov, "test-model", f.workDir, nil, 0, 3) - if _, err := m.Chat(ctx, f.expID, 0, nil, f.ts, "probe goal", "status?", passHooks{}, nil, nil, nil, nil, nil); err != nil { + case "pentest": + c := NewChatAgent(prov, "test-model", t.TempDir(), nil, 0) + c.SetGuard(guard.New()) + if _, err := c.Chat(ctx, "pentest", "conv-dial-pentest", "fetch it", 3, 0, false, nil); err != nil { t.Fatal(err) } case "chat": @@ -159,11 +160,11 @@ func runAgentKind(t *testing.T, kind string, f hookReachFixture, ctx context.Con } } -// Each agent kind's WebFetch reaches a pinned name at its pinned address, and -// once the name answers another address it connects nowhere and asks. A fifth -// agent kind built without the dialer fails this table once it is added to it. +// Each agent kind that carries WebFetch reaches a pinned name at its pinned +// address, and once the name answers another address it connects nowhere and +// asks. Orchestration-only agents (auto, mainagent) carry no WebFetch at all. func TestWebFetchDialerWiredOnEveryAgentKind(t *testing.T) { - for _, kind := range []string{"worker", "planner", "mainagent", "chat"} { + for _, kind := range []string{"worker", "planner", "pentest", "chat"} { t.Run(kind, func(t *testing.T) { f := newHookReachFixture(t) d := testDB(t) diff --git a/agent/webfetch_redirect_test.go b/agent/webfetch_redirect_test.go index 0d2bc7af..32112fba 100644 --- a/agent/webfetch_redirect_test.go +++ b/agent/webfetch_redirect_test.go @@ -97,15 +97,15 @@ func fetchInputJSON(u string) string { return string(b) } -// Each agent kind runs a scripted WebFetch on a URL that redirects to a target -// no pin covers. The hooks let the call run, so the hop is what the gate sees: -// each kind must stop at the hop, leave the redirect target untouched and open -// one request for it. A fifth agent kind added without the redirect policy -// fails this table once it is added to it. The origin is pinned first: the +// Each agent kind that carries WebFetch runs a scripted WebFetch on a URL that +// redirects to a target no pin covers. The hooks let the call run, so the hop +// is what the gate sees: each kind must stop at the hop, leave the redirect +// target untouched and open one request for it. Orchestration-only agents +// (auto, mainagent) carry no WebFetch at all. The origin is pinned first: the // hooks never check it here, and the pinned dialer (step 2.1) connects only to // a pinned target. func TestWebFetchRedirectCheckWiredOnEveryAgentKind(t *testing.T) { - for _, kind := range []string{"worker", "planner", "mainagent", "chat"} { + for _, kind := range []string{"worker", "planner", "pentest", "chat"} { t.Run(kind, func(t *testing.T) { f := newHookReachFixture(t) d := testDB(t) @@ -133,9 +133,10 @@ func TestWebFetchRedirectCheckWiredOnEveryAgentKind(t *testing.T) { if _, _, err := p.Plan(ctx, f.expID, nil, f.ts, "probe goal", nil, passHooks{}, nil); err != nil { t.Fatal(err) } - case "mainagent": - m := NewMainAgent(prov, "test-model", f.workDir, nil, 0, 3) - if _, err := m.Chat(ctx, f.expID, 0, nil, f.ts, "probe goal", "status?", passHooks{}, nil, nil, nil, nil, nil); err != nil { + case "pentest": + c := NewChatAgent(prov, "test-model", t.TempDir(), nil, 0) + c.SetGuard(guard.New()) + if _, err := c.Chat(ctx, "pentest", "conv-redirect-pentest", "fetch it", 3, 0, false, nil); err != nil { t.Fatal(err) } case "chat": diff --git a/db/db.go b/db/db.go index 2f257ab5..93a9c366 100644 --- a/db/db.go +++ b/db/db.go @@ -312,11 +312,12 @@ ON CONFLICT (agent_id, var_name) DO UPDATE if _, err := d.Exec(`DELETE FROM agent_prompt_vars WHERE var_name IN ('EngagementTitle', 'CoverageGaps', 'Now')`); err != nil { return fmt.Errorf("cleanup renamed vars: %w", err) } - // Default-on interactive_shell for the runtime agents (planner/worker/mainagent/auto) + // Default-on interactive_shell for the execution agents (planner/worker) // ONCE — respects a later user toggle-off (guarded by a settings flag). goals(one-shot - // decomposer) stays off. Runs after the column exists (schema applied before seed). + // decomposer) and pure orchestrators (mainagent/auto) stay off. Runs after the column + // exists (schema applied before seed). if v, _, _ := d.GetSetting("interactive_shell_default_v1"); v != "true" { - if _, err := d.Exec(`UPDATE agents SET interactive_shell=true WHERE key IN ('planner','worker','mainagent','auto')`); err != nil { + if _, err := d.Exec(`UPDATE agents SET interactive_shell=true WHERE key IN ('planner','worker')`); err != nil { return fmt.Errorf("seed interactive_shell defaults: %w", err) } _ = d.SetSetting("interactive_shell_default_v1", "true") @@ -406,7 +407,7 @@ ON CONFLICT DO NOTHING`, r.kind, r.pattern, r.note); err != nil { // declares `mcps: ScopeSentry`, which only takes effect once it's made visible and // that MCP is enabled/configured. var builtinSkillVisibility = map[string][]string{ - "api-recon": {"auto", "pentest", "worker"}, + "api-recon": {"pentest", "worker"}, } // seedBuiltinSkillVisibility binds the shipped built-in skills to their default diff --git a/db/skill_visibility_test.go b/db/skill_visibility_test.go index 8e87d926..e9ab7ce1 100644 --- a/db/skill_visibility_test.go +++ b/db/skill_visibility_test.go @@ -27,7 +27,7 @@ func skillRowState(t *testing.T, d *DB, agentID int64, skill string) (exists, en // TestSkillVisibilityOffIsNotResurrectedBySeed pins the behaviour the seed policy // comment already claims: a toggle-off survives the next startup. // -// The seeded map is api-recon -> {auto, pentest, worker}; the agents it names are +// The seeded map is api-recon -> {pentest, worker}; the agents it names are // restored in cleanup so running this suite against a live dev database leaves no // changed tool surface behind. func TestSkillVisibilityOffIsNotResurrectedBySeed(t *testing.T) { diff --git a/server/assembly.go b/server/assembly.go index 49c50499..c4a495dc 100644 --- a/server/assembly.go +++ b/server/assembly.go @@ -36,47 +36,48 @@ func wireAgentAugment(pg *db.DB, skillDir string, hostTools func() ([]actool.Cor } var extra []actool.CoreTool - // --- skills: load visible skills into reg (used for the Skill meta-tool - // and to know which MCP servers are skill-gated). --- + // --- skills & MCP: Auto is a pure orchestration agent and never receives + // the Skill meta-tool or MCP execution tools (it dispatches via spawn_task + // and manages skills/MCP through platform tools instead). --- var reg *skill.Registry - if names, _ := pg.AgentSkillNames(a.ID); len(names) > 0 { - nameSet := make(map[string]bool, len(names)) - for _, n := range names { - nameSet[n] = true - } - if allReg, err := loadSkillsConfined(skillDir); err == nil && allReg != nil { - reg = skill.NewRegistry() - for _, s := range allReg.List() { - // match by directory name (Base of Dir), not by skill display Name - if s.Dir != "" && nameSet[filepath.Base(s.Dir)] { - reg.Add(s) - } - } - if len(reg.List()) == 0 { - reg = nil - } - } - } - // A server named by any visible skill's `mcps:` is skill-gated: its tools - // are deferred + locked (not in the global block) until that skill loads. - gated := map[string]bool{} - if reg != nil { - for _, s := range reg.List() { - for _, srv := range s.MCPs { - gated[srv] = true - } - } - } - - // --- mcp: connect enabled servers that are directly visible to this agent - // OR skill-gated (named in a visible skill's mcps field). Directly-visible - // and NOT gated → global (unlocked from session start). Skill-gated → - // deferred until that skill is invoked (regardless of direct visibility). var closers []io.Closer serverTools := map[string][]string{} // server name → its tool names var allNames, globalNames []string globalSet := map[string]bool{} - { + if agentKey != "auto" { + if names, _ := pg.AgentSkillNames(a.ID); len(names) > 0 { + nameSet := make(map[string]bool, len(names)) + for _, n := range names { + nameSet[n] = true + } + if allReg, err := loadSkillsConfined(skillDir); err == nil && allReg != nil { + reg = skill.NewRegistry() + for _, s := range allReg.List() { + // match by directory name (Base of Dir), not by skill display Name + if s.Dir != "" && nameSet[filepath.Base(s.Dir)] { + reg.Add(s) + } + } + if len(reg.List()) == 0 { + reg = nil + } + } + } + // A server named by any visible skill's `mcps:` is skill-gated: its tools + // are deferred + locked (not in the global block) until that skill loads. + gated := map[string]bool{} + if reg != nil { + for _, s := range reg.List() { + for _, srv := range s.MCPs { + gated[srv] = true + } + } + } + + // --- mcp: connect enabled servers that are directly visible to this agent + // OR skill-gated (named in a visible skill's mcps field). Directly-visible + // and NOT gated → global (unlocked from session start). Skill-gated → + // deferred until that skill is invoked (regardless of direct visibility). mcpIDs, _ := pg.AgentVisible(a.ID, "mcp") want := idSet(mcpIDs) all, _ := pg.ListMCP() @@ -326,10 +327,10 @@ func wireTools(pg *db.DB, domainReg map[string]actool.CoreTool) { } } // interactive shell: gated purely by the agent's interactive_shell flag (like - // web_search), NOT by tools-table binding. When on, inject the 5 shell_* tools - // and COUPLE the Bash description addendum so it points at shell_open — and never - // dangles when off. See docs/interactive-shell-design.md §14.2. - if !actool.InteractiveShellDisabled() { + // web_search), NOT by tools-table binding. Orchestration-only agents (auto, + // mainagent) have no shell execution tools and never receive shell_* even if + // an older DB had interactive_shell=true. See docs/interactive-shell-design.md §14.2. + if agentKey != "auto" && agentKey != "mainagent" && !actool.InteractiveShellDisabled() { if a, err := pg.GetAgentByKey(agentKey); err == nil && a != nil && a.InteractiveShell { out = append(out, actool.ShellSessionTools()...) for i, t := range out { diff --git a/server/orchestration.go b/server/orchestration.go index 9b90deb7..a210e83b 100644 --- a/server/orchestration.go +++ b/server/orchestration.go @@ -169,11 +169,34 @@ func (s *Server) delegateToTask(ctx context.Context, in json.RawMessage, pick fu if s.m.Assets() != nil { tsx.SetAssetStore(s.m.Assets(), s.m.Assets().Companies()) } - tsx.SetNotify(t.Notify) // generic wake-up (write ops without a dedicated callback go through it; no-op for read tools) - tsx.SetNotifyHint(t.NotifyHint) // add_hint → records an "orchestrator added N strategic hints: ..." entry and wakes the planner + tsx.SetNotify(t.Notify) // generic wake-up (write ops without a dedicated callback go through it; no-op for read tools) + tsx.SetResumeTask(func() { s.reviveTask(t) }) // set_goals → pulls a completed/paused task back to running + tsx.SetNotifyGoal(t.NotifyGoal) // set_goals → records a goal-added trigger and wakes the planner + tsx.SetNotifyHint(t.NotifyHint) // add_hint → records an "orchestrator added N strategic hints: ..." entry and wakes the planner return pick(tsx).Call(ctx, inner, nil) } +// buildDomainReg extends buildDomainReg(as) with task_id-delegating wrappers +// for set_goals and set_constraints so task-less orchestration agents (Auto) +// can manage goals and constraints on existing tasks via the same tool keys +// without colliding with per-task MainAgent/Goals instances. +func (s *Server) buildDomainReg() map[string]actool.CoreTool { + reg := buildDomainReg(s.m.Assets()) + if reg == nil { + reg = make(map[string]actool.CoreTool) + } + ts := agent.NewToolSet(nil, "") + sg := ts.SetGoalsTool() + reg["set_goals"] = wrTool("set_goals", sg.Description(), sg.InputSchema(), func(ctx context.Context, in json.RawMessage) (actool.Result, error) { + return s.delegateToTask(ctx, in, (*agent.ToolSet).SetGoalsTool) + }) + sc := ts.SetConstraintsTool() + reg["set_constraints"] = wrTool("set_constraints", sc.Description(), sc.InputSchema(), func(ctx context.Context, in json.RawMessage) (actool.Result, error) { + return s.delegateToTask(ctx, in, (*agent.ToolSet).SetConstraintsTool) + }) + return reg +} + // --- tools --- func (s *Server) toolListTasks() actool.CoreTool { @@ -252,7 +275,7 @@ func (s *Server) toolSpawnTask() actool.CoreTool { "llm_profile_id": map[string]any{"type": "integer", "description": "optional: the LLM profile id this subtask's planner/worker uses (see list_llm_profiles); empty inherits the parent task, then falls back to the global active profile"}, "timeout_seconds": map[string]any{"type": "integer", "description": "optional: task-level timeout (seconds). When it fires, a graceful wrap-up runs and the task enters the timeout terminal state; empty or 0 = no time limit"}, "plan_heartbeat_seconds": map[string]any{"type": "integer", "description": "optional: planner heartbeat interval (seconds). When this much time has passed since the last planning round ended/the task started with no trigger in between → run one planning round (deadlock backstop + wakes the planner to supervise in-flight workers). Empty or 0 = default 600 (10min);"}, - "seed_first_intent": map[string]any{"type": "boolean", "description": "optional: enable for simple tasks to issue one seed intent at creation (content = description + goal) so a worker can start testing right away without waiting for the first planner round; default false (the standard plan-then-execute flow)."}, + "seed_first_intent": map[string]any{"type": "boolean", "description": "optional: pass true to issue one seed intent at creation (content = description + goal) so a worker starts immediately without waiting for the first planner round (Auto should pass true when dispatching a user target/objective); default false (the standard plan-then-execute flow)."}, }, "description", "goal"), func(ctx context.Context, in json.RawMessage) (actool.Result, error) { var a struct { @@ -552,6 +575,7 @@ func (s *Server) seedOrchestrationTools() { } s.refreshBuiltinToolSchemas() s.seedAutoDefaultBindings() + s.seedAutoGoalConstraintBindings() s.seedPlannerDefaultBindings() s.seedPlannerListAssetsBinding() s.seedCompanyScopeRebind() @@ -562,7 +586,8 @@ func (s *Server) seedOrchestrationTools() { s.seedAutoReportFindingBinding() s.unbindGoalMetDefault() s.reseedGoalsPrompt() // goals prompt gains the "extract operation constraints" step → old DBs append a new default version (one-time) - s.reseedMainAgentPrompt() // mainagent prompt gains "after goals are met, ask via add_intent whether to register a goal" (one-time) + s.reseedMainAgentPrompt() // mainagent prompt updated to orchestration-only (no shell/file/HTTP tools) → old DBs append a new default version (one-time) + s.reseedAutoPrompt() // auto prompt hardened with explicit spawn_task(seed_first_intent=true) dispatch rules (one-time) s.reseedPlannerPrompt() // planner prompt: rewrites the "zero intents" justification rules + adds quantitative acceptance checks (one-time) s.reseedWorkerPrompt() // worker prompt: adds the evidence bar for negative conclusions (one-time) s.seedReporterAgent() // seeds the "report writer" agent + tool bindings + finding trigger (one-time) @@ -746,7 +771,7 @@ func (s *Server) reseedGoalsPrompt() { // in history, and users who customized can recover from the version record. settings flag guard → done only once. Fresh DBs need nothing // (SeedPromptIfEmpty already seeds the latest default). Structurally identical to reseedGoalsPrompt. func (s *Server) reseedMainAgentPrompt() { - const flag = "mainagent_prompt_goalless_intent_v1" + const flag = "mainagent_prompt_orchestrator_v2" if v, _, _ := s.m.pg.GetSetting(flag); v == "true" { return } @@ -767,7 +792,33 @@ func (s *Server) reseedMainAgentPrompt() { log.Printf("[prompts] failed to refresh mainagent prompt to the new default: %v", err) return } - log.Printf("[prompts] mainagent prompt: appended a new default version (adds the ask-about-registering-a-goal-after-met step, one-time)") + log.Printf("[prompts] mainagent prompt: appended a new default version (orchestration-only rules, one-time)") +} + +// reseedAutoPrompt refreshes the Auto agent prompt to the hardened orchestration +// default on existing DBs (once per flag; old versions remain in prompt history). +func (s *Server) reseedAutoPrompt() { + const flag = "auto_prompt_orchestrator_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] failed to refresh auto prompt to the new default: %v", err) + return + } + log.Printf("[prompts] auto prompt: appended a new default version (explicit dispatch rules, one-time)") } // reseedPlannerPrompt refreshes the planner prompt to [the current code default] — the default body was slimmed down and "restraint" demoted to @@ -1088,11 +1139,38 @@ func (s *Server) seedAutoDefaultBindings() { keys = append(keys, t.Name()) } keys = append(keys, platformToolKeys...) - // Asset tools: Auto operating the platform often views/registers assets and manages company scopes. - keys = append(keys, "insert_assets", "add_company_scope", "list_assets") + // Asset & task-goal tools: Auto operating the platform views/registers assets, + // manages company scopes, and adds goals/constraints to existing tasks. + keys = append(keys, "insert_assets", "add_company_scope", "list_assets", "set_goals", "set_constraints") if err := s.m.pg.AddAgentToToolBinding("auto", keys); err != nil { log.Printf("[auto] default binding failed: %v", err) return } _ = s.m.pg.SetSetting(flag, "true") } + +// seedAutoGoalConstraintBindings binds set_goals and set_constraints onto "auto" +// and refreshes their stored schemas (adding the optional task_id property) ONCE +// on existing DBs. Fresh DBs already get both from BuiltinToolSeeds(). +func (s *Server) seedAutoGoalConstraintBindings() { + const flag = "auto_goal_constraint_bindings_v1" + if v, _, _ := s.m.pg.GetSetting(flag); v == "true" { + return + } + if err := s.m.pg.AddAgentToToolBinding("auto", []string{"set_goals", "set_constraints"}); err != nil { + log.Printf("[auto] set_goals/set_constraints default binding failed: %v", err) + return + } + refresh := map[string]bool{"set_goals": true, "set_constraints": true} + for _, sd := range agent.BuiltinToolSeeds() { + if !refresh[sd.Key] { + continue + } + schema, _ := json.Marshal(sd.Schema) + if err := s.m.pg.RefreshToolDefaults(sd.Key, sd.Desc, schema); err != nil { + log.Printf("[tools] refresh %s schema failed: %v", sd.Key, err) + return + } + } + _ = s.m.pg.SetSetting(flag, "true") +} diff --git a/server/orchestrator_tools_test.go b/server/orchestrator_tools_test.go new file mode 100644 index 00000000..db0b3cea --- /dev/null +++ b/server/orchestrator_tools_test.go @@ -0,0 +1,202 @@ +package server + +import ( + "context" + "encoding/json" + "iter" + "os" + "path/filepath" + "strings" + "sync" + "testing" + + "github.com/Autumn-27/artex/agent" + "github.com/Autumn-27/norma/llm" + actool "github.com/Autumn-27/norma/tool" +) + +type captureToolsLLM struct { + mu sync.Mutex + names []string +} + +func (p *captureToolsLLM) record(req llm.CompletionRequest) { + p.mu.Lock() + defer p.mu.Unlock() + if p.names != nil { + return + } + p.names = make([]string, 0, len(req.Tools)) + for _, t := range req.Tools { + p.names = append(p.names, t.Name) + } +} + +func (p *captureToolsLLM) set() map[string]bool { + p.mu.Lock() + defer p.mu.Unlock() + out := make(map[string]bool, len(p.names)) + for _, n := range p.names { + out[n] = true + } + return out +} + +func (p *captureToolsLLM) Complete(_ context.Context, req llm.CompletionRequest) (llm.Message, string, llm.Usage, error) { + p.record(req) + return llm.Message{Role: llm.RoleAssistant, Content: []llm.ContentBlock{llm.TextBlock("ok")}}, "end_turn", llm.Usage{}, nil +} + +func (p *captureToolsLLM) Stream(_ context.Context, req llm.CompletionRequest) iter.Seq2[llm.StreamEvent, error] { + p.record(req) + return func(yield func(llm.StreamEvent, error) bool) { + yield(llm.StreamEvent{Type: llm.SETextDelta, Text: "ok"}, nil) + yield(llm.StreamEvent{Type: llm.SEMessageDelta, StopReason: "end_turn"}, nil) + } +} + +// TestServerOrchestratorToolsAndCrossTaskGoals verifies issue #544 end-to-end +// with the real server tool wiring (wireAgentAugment + wireTools + +// seedOrchestrationTools) against Postgres: +// - auto receives spawn_task, add_task_hint, set_goals, set_constraints and +// never receives Bash/Read/Write/Edit/WebFetch/Skill/shell_open even when a +// skill is visible in the DB or interactive_shell=true is set on auto; +// - auto's delegated set_goals and set_constraints write to the target task; +// - mainagent never receives Bash/Write/Edit/WebFetch/shell_open; +// - pentest and worker keep Bash, WebFetch, Skill, and shell_open. +func TestServerOrchestratorToolsAndCrossTaskGoals(t *testing.T) { + skipWithoutDSN(t) + m, err := NewManager(t.TempDir(), "") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = m.Close() }) + t.Cleanup(func() { + agent.SetToolAugment(nil) + agent.SetToolResolve(nil) + }) + + skillDir := t.TempDir() + const skillName = "t-orch-544" + if err := os.MkdirAll(filepath.Join(skillDir, skillName), 0o755); err != nil { + t.Fatal(err) + } + md := "---\nname: t-orch-544\ndescription: fixture skill\n---\nfixture" + if err := os.WriteFile(filepath.Join(skillDir, skillName, "SKILL.md"), []byte(md), 0o644); err != nil { + t.Fatal(err) + } + + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + s := New(ctx, m, skillDir, m.dir, t.TempDir()) + pg := m.pg + + // Even if an older DB has a skill visible to auto and interactive_shell=true + // on auto/mainagent, runtime assembly must keep execution tools off them. + for _, key := range []string{"auto", "mainagent", "pentest", "worker"} { + ag, err := pg.GetAgentByKey(key) + if err != nil || ag == nil { + t.Fatalf("missing built-in agent %q: %v", key, err) + } + origSkills, _ := pg.AgentSkillNames(ag.ID) + origShell := ag.InteractiveShell + t.Cleanup(func() { + _ = pg.SetAgentSkillVisibility(ag.ID, origSkills) + _, _ = pg.Exec(`UPDATE agents SET interactive_shell=$2 WHERE id=$1`, ag.ID, origShell) + }) + if err := pg.ToggleSkillVisibility(ag.ID, skillName, true); err != nil { + t.Fatal(err) + } + if _, err := pg.Exec(`UPDATE agents SET interactive_shell=true WHERE id=$1`, ag.ID); err != nil { + t.Fatal(err) + } + } + + // 1. Auto chat tool surface + autoProv := &captureToolsLLM{} + autoChat := agent.NewChatAgent(autoProv, "test-model", m.dir, nil, 100000) + if _, err := autoChat.Chat(ctx, "auto", "conv-auto-srv-544", "recon https://example.com", 1, 0, false, nil); err != nil { + t.Fatal(err) + } + autoTools := autoProv.set() + for _, want := range []string{"spawn_task", "add_task_hint", "set_goals", "set_constraints", "list_tasks", "get_task_graph", "list_task_findings", "list_assets"} { + if !autoTools[want] { + t.Errorf("auto missing %q", want) + } + } + for _, bad := range []string{"Bash", "Read", "Write", "Edit", "MultiEdit", "LS", "Glob", "Grep", "WebFetch", "Skill", "shell_open", "shell_send"} { + if autoTools[bad] { + t.Errorf("auto must not expose %q", bad) + } + } + + // 2. MainAgent tool surface + task, err := m.CreateTask("issue 544 test", "verify orchestration", nil, 0, 0) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _, _ = m.DeleteTask(task.ID, DeleteTaskOptions{}) }) + mainProv := &captureToolsLLM{} + ma := agent.NewMainAgent(mainProv, "test-model", m.dir, nil, 0, 1) + if _, err := ma.Chat(ctx, task.ExpID, 0, m.Assets(), task.Store, task.Goal, "status?", nil, nil, nil, nil, nil, nil); err != nil { + t.Fatal(err) + } + mainTools := mainProv.set() + for _, want := range []string{"graph_overview", "add_hint", "add_intent", "set_goals", "set_constraints"} { + if !mainTools[want] { + t.Errorf("mainagent missing %q", want) + } + } + for _, bad := range []string{"Bash", "Read", "Write", "Edit", "WebFetch", "shell_open", "shell_send"} { + if mainTools[bad] { + t.Errorf("mainagent must not expose %q", bad) + } + } + + // 3. Pentest solo chat keeps Bash, WebFetch, Skill, and shell_open + pentestProv := &captureToolsLLM{} + pentestChat := agent.NewChatAgent(pentestProv, "test-model", m.dir, nil, 100000) + if _, err := pentestChat.Chat(ctx, "pentest", "conv-pentest-srv-544", "hello", 1, 0, false, nil); err != nil { + t.Fatal(err) + } + pentestTools := pentestProv.set() + for _, want := range []string{"Bash", "WebFetch", "Skill", "shell_open"} { + if !pentestTools[want] { + t.Errorf("pentest missing %q", want) + } + } + + // 4. Auto's delegated set_goals and set_constraints operate on task_id + resolvedAuto, _, cleanup := agent.AugmentTools(ctx, "auto", nil) + defer cleanup() + byName := map[string]actool.CoreTool{} + for _, tl := range resolvedAuto { + byName[tl.Name()] = tl + } + sg := byName["set_goals"] + if sg == nil { + t.Fatal("auto resolved tools missing set_goals") + } + res, err := sg.Call(ctx, json.RawMessage(`{"task_id":"`+task.ID+`","text":"Confirm auth bypass on /admin"}`), nil) + if err != nil || res.IsError { + t.Fatalf("auto set_goals failed: err=%v out=%s", err, res.Flatten()) + } + goals, err := task.Store.ListByKind("goal", 10) + if err != nil || len(goals) != 1 || !strings.Contains(string(goals[0].Payload), "Confirm auth bypass") { + t.Fatalf("task goals after auto set_goals = %+v, err=%v", goals, err) + } + + sc := byName["set_constraints"] + if sc == nil { + t.Fatal("auto resolved tools missing set_constraints") + } + res, err = sc.Call(ctx, json.RawMessage(`{"task_id":"`+task.ID+`","text":"passive recon only","type":"deny"}`), nil) + if err != nil || res.IsError { + t.Fatalf("auto set_constraints failed: err=%v out=%s", err, res.Flatten()) + } + cs, err := task.Store.ListConstraints() + if err != nil || len(cs) != 1 || cs[0].Text != "passive recon only" { + t.Fatalf("task constraints after auto set_constraints = %+v, err=%v", cs, err) + } + _ = s +} diff --git a/server/server.go b/server/server.go index d2d85f57..602573a2 100644 --- a/server/server.go +++ b/server/server.go @@ -276,7 +276,7 @@ func New(ctx context.Context, m *Manager, skillDir string, dataDir string, keyDi return a.TaskTimeoutWrapupMaxTurns, true }) wireAgentAugment(m.pg, s.skillDir, s.hostTools, s.execPriv) // wire visible skills/MCP + traffic/orchestration host tools into the agent toolset - domainReg := buildDomainReg(m.Assets()) + domainReg := s.buildDomainReg() wireTools(m.pg, domainReg) // built-in tools table: filter per agent + override description/schema + inject defaults seedPrompts(m.pg) // seed built-in agent default prompt bodies into agent_prompts (only when empty) warnBrokenSkills(s.skillDir) // surface skills whose frontmatter silently failed to parse diff --git a/server/target_gate_scope_test.go b/server/target_gate_scope_test.go index bd42b93c..440f38e9 100644 --- a/server/target_gate_scope_test.go +++ b/server/target_gate_scope_test.go @@ -97,10 +97,15 @@ type scopeProbe struct { type scopeProbeProvider struct { seen chan scopeProbe turn atomic.Int64 + tool string } func newScopeProbeProvider() *scopeProbeProvider { - return &scopeProbeProvider{seen: make(chan scopeProbe, 16)} + return newScopeProbeProviderFor("LS") +} + +func newScopeProbeProviderFor(tool string) *scopeProbeProvider { + return &scopeProbeProvider{seen: make(chan scopeProbe, 16), tool: tool} } func (p *scopeProbeProvider) Stream(ctx context.Context, _ llm.CompletionRequest) iter.Seq2[llm.StreamEvent, error] { @@ -111,8 +116,12 @@ func (p *scopeProbeProvider) Stream(ctx context.Context, _ llm.CompletionRequest } events := []llm.StreamEvent{{Type: llm.SETextDelta, Text: "done"}, {Type: llm.SEMessageDelta, StopReason: "end_turn"}} if p.turn.Add(1) == 1 { + tool := p.tool + if tool == "" { + tool = "LS" + } events = []llm.StreamEvent{ - {Type: llm.SEToolUseStart, ToolID: "call-1", ToolName: "LS"}, + {Type: llm.SEToolUseStart, ToolID: "call-1", ToolName: tool}, {Type: llm.SEToolInputJSON, Text: `{}`}, {Type: llm.SEMessageDelta, StopReason: "tool_use"}, } @@ -236,7 +245,7 @@ func (f *targetScopeFixture) finalPlannerRound(t *testing.T, task *Task) scopePr func (f *targetScopeFixture) mainAgentTurn(t *testing.T, task *Task) scopeProbe { t.Helper() - probe := newScopeProbeProvider() + probe := newScopeProbeProviderFor("graph_overview") f.s.cfgMu.Lock() f.s.llmOn, f.s.llmProv = true, probe f.s.cfgMu.Unlock() @@ -311,11 +320,12 @@ func TestEveryAgentKindCarriesTargetScope(t *testing.T) { run func(*testing.T, *Task) scopeProbe wait time.Duration targetOnly bool // the session runs on Task.TargetGuard, not Task.Guard + wantTool string }{ - {"planner round", f.plannerLoopRound, intercept.DefaultTargetWaitBound, true}, - {"final planner round", f.finalPlannerRound, 0, true}, - {"main-agent turn", f.mainAgentTurn, intercept.DefaultTargetWaitBound, true}, - {"worker intent", f.workerIntent, intercept.DefaultTargetWaitBound, false}, + {"planner round", f.plannerLoopRound, intercept.DefaultTargetWaitBound, true, "LS"}, + {"final planner round", f.finalPlannerRound, 0, true, "LS"}, + {"main-agent turn", f.mainAgentTurn, intercept.DefaultTargetWaitBound, true, "graph_overview"}, + {"worker intent", f.workerIntent, intercept.DefaultTargetWaitBound, false, "LS"}, } for _, site := range taskSites { t.Run(site.name, func(t *testing.T) { @@ -324,11 +334,11 @@ func TestEveryAgentKindCarriesTargetScope(t *testing.T) { task.TargetGuard = recorder got := site.run(t, task) onTarget, onMain := auditedTools(recorder), auditedTools(task.Guard) - if site.targetOnly && (len(onTarget) != 1 || onTarget[0] != "LS" || len(onMain) != 0) { - t.Fatalf("tool calls seen by TargetGuard=%v Guard=%v, want one LS on TargetGuard only", onTarget, onMain) + if site.targetOnly && (len(onTarget) != 1 || onTarget[0] != site.wantTool || len(onMain) != 0) { + t.Fatalf("tool calls seen by TargetGuard=%v Guard=%v, want one %s on TargetGuard only", onTarget, onMain, site.wantTool) } - if !site.targetOnly && (len(onMain) != 1 || onMain[0] != "LS" || len(onTarget) != 0) { - t.Fatalf("tool calls seen by TargetGuard=%v Guard=%v, want one LS on Guard only", onTarget, onMain) + if !site.targetOnly && (len(onMain) != 1 || onMain[0] != site.wantTool || len(onTarget) != 0) { + t.Fatalf("tool calls seen by TargetGuard=%v Guard=%v, want one %s on Guard only", onTarget, onMain, site.wantTool) } if !got.ok || got.scope.TaskID != task.ID || got.scope.ConversationID != 0 { t.Fatalf("scope = %+v (present=%v), want task %s", got.scope, got.ok, task.ID)