mirror of
https://github.com/skilfoy/ARTEX-English.git
synced 2026-12-03 21:17:24 +00:00
200 lines
12 KiB
Go
200 lines
12 KiB
Go
package agent
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
|
|
"github.com/Autumn-27/norma/agentcore"
|
|
"github.com/Autumn-27/norma/llm"
|
|
"github.com/Autumn-27/norma/permission"
|
|
actool "github.com/Autumn-27/norma/tool"
|
|
"github.com/Autumn-27/norma/transcript"
|
|
"github.com/skilfoy/ARTEX-English/db"
|
|
"github.com/skilfoy/ARTEX-English/intercept"
|
|
)
|
|
|
|
// MainAgent is the thin human-interface orchestrator (docs §4.2 / §7). The human
|
|
// chats with it; it observes (read tools), and steers by injecting hints
|
|
// (→planner) or direct high-priority intents (→frontier). It does NOT run the
|
|
// autonomous intent-generation loop (that is the planner's job).
|
|
type MainAgent struct {
|
|
findingRecorder FindingRecorder
|
|
prov llm.Provider
|
|
model string
|
|
tx *transcript.Store // raw LLM conversation persistence (nil = off)
|
|
window int // context window in tokens (for compaction)
|
|
windowFn func() int // optional dynamic task-chain minimum
|
|
maxTurns int // max agent turns per run (0 = unlimited)
|
|
proxyAddr string // recording proxy for WebFetch (empty = direct)
|
|
proxyCACert string // recording proxy's CA cert path (HTTPS verify)
|
|
webSearch WebSearchOpts // web_search tool backend selection (off by default)
|
|
workDir string // shared work dir (surfaced in prompt as artifact-output target)
|
|
steerWork func(intentID int64, msg string) error // engine callback: steer a running work (nil = off)
|
|
nonStreamingFn func() bool // resolver: use non-streaming (Complete) path? (nil = streaming)
|
|
noaEnabledFn func() bool // resolver: use experimental noa compaction? (nil = off)
|
|
maxTokensFn func() int // resolver: per-reply output cap (nil/0 = send no cap)
|
|
}
|
|
|
|
// SetNoaEnabled wires a resolver deciding whether runs use the experimental noa
|
|
// context-compression mechanism. nil/unset = off (built-in compaction). Read per
|
|
// run so the settings toggle takes effect without rebuilding the agent.
|
|
func (m *MainAgent) SetNoaEnabled(fn func() bool) { m.noaEnabledFn = fn }
|
|
|
|
// SetNonStreaming wires a resolver deciding whether runs use the non-streaming
|
|
// model path (true = non-streaming). nil/unset = streaming (default).
|
|
func (m *MainAgent) SetNonStreaming(fn func() bool) { m.nonStreamingFn = fn }
|
|
|
|
func (m *MainAgent) nonStreaming() bool { return m.nonStreamingFn != nil && m.nonStreamingFn() }
|
|
|
|
// SetMaxTokens wires a resolver for the per-reply output cap. nil/unset or 0 =
|
|
// send no cap and let the endpoint decide. Read per run, like nonStreaming.
|
|
func (m *MainAgent) SetMaxTokens(fn func() int) { m.maxTokensFn = fn }
|
|
|
|
func (m *MainAgent) maxTokens() int {
|
|
if m.maxTokensFn == nil {
|
|
return 0
|
|
}
|
|
return m.maxTokensFn()
|
|
}
|
|
|
|
func NewMainAgent(prov llm.Provider, model, workDir string, tx *transcript.Store, window, maxTurns int) *MainAgent {
|
|
return &MainAgent{prov: prov, model: model, workDir: workDir, tx: tx, window: window, maxTurns: maxTurns}
|
|
}
|
|
|
|
func (m *MainAgent) SetCompactionWindowResolver(fn func() int) { m.windowFn = fn }
|
|
|
|
func (m *MainAgent) compactionWindow() int {
|
|
if m.windowFn != nil {
|
|
return m.windowFn()
|
|
}
|
|
return m.window
|
|
}
|
|
|
|
// SetProxy points the main agent's WebFetch at the recording proxy plus the CA
|
|
// cert it trusts to verify HTTPS through it (empty addr = direct).
|
|
func (m *MainAgent) SetProxy(addr, caCert string) { m.proxyAddr, m.proxyCACert = addr, caCert }
|
|
|
|
// SetWebSearch selects the web_search backend for the main agent (off by default).
|
|
func (m *MainAgent) SetWebSearch(o WebSearchOpts) { m.webSearch = o }
|
|
|
|
// SetSteerWork wires the engine callback that lets the main agent's steer_work
|
|
// tool inject a mid-run course-correction into a running work (nil = tool off).
|
|
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 spec tail is code-owned (artifactSpec), appended after rendering.
|
|
const mainAgentDefaultTmpl = `You are the main agent in an authorized security assessment. You are the operator's interface to the task. Observe progress and carry out operator instructions through platform tools. The planner generates routine exploration intents and workers execute them. Respond in English.
|
|
|
|
Use graph_overview, list_findings, list_facts, list_assets, and get_worker_output to answer questions about recorded progress. Base every status statement on tool results.
|
|
|
|
Use add_hint for a requested shift in emphasis or direction that the planner should consider. Use add_intent with high priority for a specific test that the operator wants to run promptly. Use steer_work to correct a running worker and kill_work to stop a worker pursuing the wrong direction. Use set_goals to add an outcome the task must achieve. Use set_constraints to record explicit operation limits or permissions; classify each as allow or deny and state its scope precisely.
|
|
|
|
If all current goals are met and a request implies a new lasting goal, state the outcome you understood and ask the operator whether to add it with set_goals. A one-time verification can proceed through add_intent without creating a new goal.
|
|
|
|
Current task goal: {{.Goal}}
|
|
|
|
Report the action taken and its observed result concisely. Do not invent findings or imply that an unverified action succeeded.`
|
|
|
|
func mainAgentSystem(goal, dataDir, workDir string) string {
|
|
body := renderSystem("mainagent", mainAgentDefaultTmpl, MainVars{Goal: goal, DataDir: dataDir, Now: nowStr()})
|
|
return body + artifactSpec(workDir)
|
|
}
|
|
|
|
// Chat handles one human message and returns the assistant reply. emit, if
|
|
// non-nil, receives each execution step (thinking / tool_use / tool_result /
|
|
// text / result) so the main-agent session shows its work — exactly like the
|
|
// worker/planner sessions — not just the final answer.
|
|
func (m *MainAgent) Chat(ctx context.Context, taskID int64, mainSeg int, as *db.AssetStore, ts *db.ExplorationStore, goal, message string, emit func(db.Activity), notify, resume func(), notifyGoal, notifyHint func([]string)) (string, error) {
|
|
tsx := NewToolSet(ts, "human")
|
|
tsx.SetFindingRecorder(m.findingRecorder)
|
|
if as != nil {
|
|
tsx.SetAssetStore(as, as.Companies())
|
|
}
|
|
tsx.SetTaskID(taskID)
|
|
tsx.SetCoverageEnabled(as == nil || as.CoverageEnabled(taskID))
|
|
tsx.SetNotify(notify) // generic wake (writes with no dedicated callback use it; debounced)
|
|
tsx.SetResumeTask(resume) // set_goals adds a goal → pull a finished or paused task back to running
|
|
tsx.SetNotifyGoal(notifyGoal) // set_goals adds a goal → record a "the operator added goals: …" trigger for the planner
|
|
tsx.SetNotifyHint(notifyHint) // add_hint adds hints → record a "the operator added N strategic hints: …" trigger for the planner
|
|
tsx.steerWork = m.steerWork // enable steer_work tool (nil = unavailable)
|
|
// Domain tools plus the base default toolset (Read/Write/Edit/MultiEdit/LS/Glob/Grep/Bash).
|
|
// When asset-coverage is off, drop add_task_scope and list_untested_assets (they stay out of the prompt).
|
|
base := append(tsx.DropCoverageTools(tsx.MainAgentTools()), actool.DefaultTools()...)
|
|
ctx = WithRunInfo(ctx, RunInfo{TaskID: taskID, ExplorationID: explorationID(ts)})
|
|
tools, def, cleanup := AugmentTools(ctx, "mainagent", base)
|
|
defer cleanup()
|
|
// This task's working directory, <workDir>/tasks/<taskID>. Create it first.
|
|
mainDir := ensureRunDir(m.workDir, taskID, 0)
|
|
ctx = intercept.WithReviewWorkingDirectory(ctx, mainDir)
|
|
system, boundary := deferredSystem(mainAgentSystem(goal, m.workDir, mainDir), def)
|
|
opts := agentcore.Options{
|
|
Provider: m.prov,
|
|
SystemPrompt: system,
|
|
DynamicBoundary: boundary,
|
|
Tools: tools,
|
|
DeferredTools: def.Deferred,
|
|
UnlockSet: def.Unlock,
|
|
PermissionMode: permission.ModeBypass,
|
|
EnableWebFetch: true, // WebFetch goes through the recording proxy and is logged like curl; the proxy CA lets MITM-resigned HTTPS certificates verify normally
|
|
WebFetchProxy: m.proxyAddr,
|
|
WebFetchCACert: m.proxyCACert,
|
|
// Optional web search. ddgs needs no key; brave-free needs BraveKey; tavily needs TavilyKey.
|
|
// WebSearchProxy is a separate egress proxy (http/https/socks5), unrelated to the traffic-recording MITM proxy. Empty means a direct connection.
|
|
EnableWebSearch: m.webSearch.Enabled,
|
|
WebSearchBackend: m.webSearch.Backend,
|
|
BraveSearchAPIKey: m.webSearch.BraveKey,
|
|
TavilySearchAPIKey: m.webSearch.TavilyKey,
|
|
DeepSeekSearchBaseURL: m.webSearch.DeepSeekBaseURL,
|
|
DeepSeekSearchAPIKey: m.webSearch.DeepSeekAPIKey,
|
|
DeepSeekSearchModel: m.webSearch.DeepSeekModel,
|
|
WebSearchProxy: m.webSearch.Proxy,
|
|
BashEnv: proxyEnv(m.proxyAddr, m.proxyCACert), // Bash child processes use the recording proxy by default and trust its CA
|
|
WorkingDir: mainDir, // this task's working directory <workDir>/tasks/<taskID>
|
|
ToolOutputDir: cmdOutDir(mainDir),
|
|
MaxTurns: m.maxTurns, // 0 = unlimited (configurable in agent management)
|
|
Compaction: compactionConfig(m.compactionWindow()), // long chats stay within the window
|
|
Todos: actool.NewTodoStore(), // Session-level scratch to-do (TodoWrite), for planning only; discarded when the session ends.
|
|
// Hitting the step budget makes the SDK run wrap-up: give the user a one-line
|
|
// progress summary. The prompt and wrap-up turn count are editable in the
|
|
// admin UI (default 10 turns).
|
|
Settlement: wrapupSettlement("mainagent", nil),
|
|
NonStreaming: m.nonStreaming(), // When the profile selects non-streaming, the run uses Provider.Complete
|
|
MaxTokens: m.maxTokens(), // 0 = no cap; the server default applies
|
|
}
|
|
if m.tx != nil { // persist raw human↔AI conversation; one accumulating file per segment
|
|
opts.Transcript = m.tx
|
|
// Segment 0 keeps the legacy "exp%d-main" name so existing transcripts still
|
|
// load; each new session (seg>=1) gets its own file for a clean context.
|
|
opts.SessionID = fmt.Sprintf("exp%d-main", ts.ID())
|
|
if mainSeg > 0 {
|
|
opts.SessionID = fmt.Sprintf("exp%d-main-s%d", ts.ID(), mainSeg)
|
|
}
|
|
}
|
|
// Experimental: when enabled, noa takes over context compression (archives live under <workDir>/noa/<SessionID> and persist).
|
|
// session id follows the same rule as the transcript (segment-aware) so the archive and restore stay aligned.
|
|
noaSession := fmt.Sprintf("exp%d-main", ts.ID())
|
|
if mainSeg > 0 {
|
|
noaSession = fmt.Sprintf("exp%d-main-s%d", ts.ID(), mainSeg)
|
|
}
|
|
enableNoa(&opts, m.noaEnabledFn, m.workDir, noaSession, noaWarn(noaSession))
|
|
ctx = attachSideCapture(ctx, &opts)
|
|
s := agentcore.NewSession(opts)
|
|
defer s.Close()
|
|
// reload the prior conversation from the transcript so the agent has context
|
|
// across turns (each Chat is a fresh session; without this it can't see earlier
|
|
// messages). First turn: no file yet → Resume loads nothing and proceeds.
|
|
if m.tx != nil {
|
|
_ = s.Resume(opts.SessionID)
|
|
}
|
|
// C2: this session is fresh each turn; re-unlock skill-gated MCPs from prior
|
|
// Skill() calls in the reloaded history so revealed tools stay callable.
|
|
seedUnlockFromHistory(s.Messages(), def.UnlockSkill)
|
|
text, _, err := captureRunSession(ctx, s, message, func(r db.Activity) {
|
|
if emit != nil {
|
|
r.Worker = "mainagent"
|
|
emit(r)
|
|
}
|
|
})
|
|
return text, err
|
|
}
|