Fully autonomous AI Agents system capable of performing complex penetration testing tasks
Go ai-agentsai-security-toolanthropicautonomous-agentsgolanggptgraphqlmulti-agent-systemoffensive-securityopen-sourceopenaipenetration-testingpenetration-testing-toolsreactsecurity-automationsecurity-testingsecurity-toolsself-hosted
feat(anthropic): adaptive thinking + Opus 4.7/4.8 (refs #288)
Sergey Kozyrenko177b138851d2
diff --git a/backend/pkg/providers/anthropic/adaptive_thinking.go b/backend/pkg/providers/anthropic/adaptive_thinking.gonew file mode 100644index 00000000..e41f0698--- /dev/null+++ b/backend/pkg/providers/anthropic/adaptive_thinking.go@@ -0,0 +1,194 @@+package anthropic++import (+ "bytes"+ "context"+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "strconv"++ "pentagi/pkg/providers/pconfig"++ "github.com/vxcontrol/langchaingo/llms"+)++type adaptiveThinkingEffortContextKey struct{}++func withAdaptiveThinkingEffort(ctx context.Context, effort string) context.Context {+ if effort == "" {+ effort = string(llms.ReasoningHigh)+ }++ return context.WithValue(ctx, adaptiveThinkingEffortContextKey{}, effort)+}++func adaptiveThinkingEffortFromContext(ctx context.Context) (string, bool) {+ effort, ok := ctx.Value(adaptiveThinkingEffortContextKey{}).(string)+ return effort, ok && effort != ""+}++// adaptiveThinkingTransport rewrites the outgoing Anthropic Messages request body+// to use adaptive thinking when the call context carries an effort (set by+// prepareCallOptions). langchaingo only emits budget thinking, but Claude Opus+// 4.7/4.8 only support thinking.type=adaptive and reject sampling params.+type adaptiveThinkingTransport struct {+ base http.RoundTripper+}++func (t *adaptiveThinkingTransport) RoundTrip(req *http.Request) (*http.Response, error) {+ effort, ok := adaptiveThinkingEffortFromContext(req.Context())+ if !ok || req.Body == nil {+ return t.base.RoundTrip(req)+ }++ body, err := io.ReadAll(req.Body)+ _ = req.Body.Close()+ if err != nil {+ return nil, fmt.Errorf("read Anthropic request body: %w", err)+ }++ updatedBody, err := rewriteAdaptiveThinkingBody(body, effort)+ if err != nil {+ return nil, err+ }++ clone := req.Clone(req.Context())+ clone.Body = io.NopCloser(bytes.NewReader(updatedBody))+ clone.ContentLength = int64(len(updatedBody))+ clone.Header.Set("Content-Length", strconv.Itoa(len(updatedBody)))+ clone.GetBody = func() (io.ReadCloser, error) {+ return io.NopCloser(bytes.NewReader(updatedBody)), nil+ }++ return t.base.RoundTrip(clone)+}++func rewriteAdaptiveThinkingBody(body []byte, effort string) ([]byte, error) {+ // langchaingo emits budget-based Anthropic thinking; adaptive thinking expects+ // thinking.type=adaptive plus a top-level output_config.effort. In the Anthropic+ // Messages API thinking and the sampling params live at the top level (unlike the+ // Bedrock Converse body).+ var payload map[string]any+ if err := json.Unmarshal(body, &payload); err != nil {+ return nil, fmt.Errorf("decode Anthropic request body: %w", err)+ }++ thinking, ok := payload["thinking"].(map[string]any)+ if !ok {+ return body, nil+ }++ thinking["type"] = "adaptive"+ // Opus 4.7/4.8 default thinking.display to "omitted" (empty reasoning text);+ // force "summarized" so reasoning stays visible in the UI.+ thinking["display"] = "summarized"+ delete(thinking, "budget_tokens")+ payload["output_config"] = map[string]any{"effort": effort}++ // Adaptive Claude models reject sampling params (Opus 4.7+ return 400 for any+ // temperature/top_p/top_k).+ delete(payload, "temperature")+ delete(payload, "top_p")+ delete(payload, "top_k")++ return json.Marshal(payload)+}++func (p *anthropicProvider) prepareCallOptions(+ ctx context.Context,+ opt pconfig.ProviderOptionsType,+ options []llms.CallOption,+) (context.Context, []llms.CallOption) {+ if !p.usesAdaptiveThinking(opt) {+ return ctx, options+ }++ reasoning, _ := p.reasoningConfigForType(opt)+ ctx = withAdaptiveThinkingEffort(ctx, string(reasoning.Effort))+ options = append(options, llms.WithReasoning(llms.ReasoningHigh, 0))++ return ctx, options+}++// usesAdaptiveThinking reports whether this agent's call must use adaptive thinking:+// either the agent config selected it, or the agent's model only supports adaptive+// (e.g. Opus 4.7/4.8, where budget thinking returns a 400).+func (p *anthropicProvider) usesAdaptiveThinking(opt pconfig.ProviderOptionsType) bool {+ if p.modelReasoningMode(opt) == pconfig.ModelReasoningAdaptiveOnly {+ return true+ }++ reasoning, ok := p.reasoningConfigForType(opt)+ return ok && reasoning.EffectiveMode() == pconfig.ReasoningModeAdaptive+}++// modelReasoningMode returns the reasoning capability declared in models.yml for+// the model assigned to this agent, or ModelReasoningNone if unknown.+func (p *anthropicProvider) modelReasoningMode(opt pconfig.ProviderOptionsType) pconfig.ModelReasoningMode {+ agentConfig := p.agentConfigForType(opt)+ if agentConfig == nil || agentConfig.Model == "" {+ return pconfig.ModelReasoningNone+ }++ for _, m := range p.models {+ if m.Name == agentConfig.Model && m.Reasoning != nil {+ return m.Reasoning.Mode+ }+ }++ return pconfig.ModelReasoningNone+}++func (p *anthropicProvider) reasoningConfigForType(opt pconfig.ProviderOptionsType) (pconfig.ReasoningConfig, bool) {+ agentConfig := p.agentConfigForType(opt)+ if agentConfig == nil || agentConfig.Reasoning.IsZero() {+ return pconfig.ReasoningConfig{}, false+ }++ return agentConfig.Reasoning, true+}++func (p *anthropicProvider) agentConfigForType(opt pconfig.ProviderOptionsType) *pconfig.AgentConfig {+ if p == nil || p.providerConfig == nil {+ return nil+ }++ switch opt {+ case pconfig.OptionsTypeSimple:+ return p.providerConfig.Simple+ case pconfig.OptionsTypeSimpleJSON:+ if p.providerConfig.SimpleJSON != nil {+ return p.providerConfig.SimpleJSON+ }+ return p.providerConfig.Simple+ case pconfig.OptionsTypePrimaryAgent:+ return p.providerConfig.PrimaryAgent+ case pconfig.OptionsTypeAssistant:+ if p.providerConfig.Assistant != nil {+ return p.providerConfig.Assistant+ }+ return p.providerConfig.PrimaryAgent+ case pconfig.OptionsTypeGenerator:+ return p.providerConfig.Generator+ case pconfig.OptionsTypeRefiner:+ return p.providerConfig.Refiner+ case pconfig.OptionsTypeAdviser:+ return p.providerConfig.Adviser+ case pconfig.OptionsTypeReflector:+ return p.providerConfig.Reflector+ case pconfig.OptionsTypeSearcher:+ return p.providerConfig.Searcher+ case pconfig.OptionsTypeEnricher:+ return p.providerConfig.Enricher+ case pconfig.OptionsTypeCoder:+ return p.providerConfig.Coder+ case pconfig.OptionsTypeInstaller:+ return p.providerConfig.Installer+ case pconfig.OptionsTypePentester:+ return p.providerConfig.Pentester+ default:+ return nil+ }+}diff --git a/backend/pkg/providers/anthropic/adaptive_thinking_test.go b/backend/pkg/providers/anthropic/adaptive_thinking_test.gonew file mode 100644index 00000000..a95b43a5--- /dev/null+++ b/backend/pkg/providers/anthropic/adaptive_thinking_test.go@@ -0,0 +1,106 @@+package anthropic++import (+ "context"+ "encoding/json"+ "io"+ "net/http"+ "net/http/httptest"+ "sync"+ "testing"++ "pentagi/pkg/config"+ "pentagi/pkg/providers/pconfig"+ "pentagi/pkg/providers/provider"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++func TestRewriteAdaptiveThinkingBody(t *testing.T) {+ body := []byte(`{+ "model": "claude-opus-4-8",+ "max_tokens": 16000,+ "temperature": 1.0,+ "top_p": 0.95,+ "thinking": {"type": "enabled", "budget_tokens": 4096},+ "messages": []+ }`)++ updatedBody, err := rewriteAdaptiveThinkingBody(body, "xhigh")+ require.NoError(t, err)++ var payload map[string]any+ require.NoError(t, json.Unmarshal(updatedBody, &payload))++ thinking := payload["thinking"].(map[string]any)+ assert.Equal(t, "adaptive", thinking["type"])+ assert.Equal(t, "summarized", thinking["display"])+ assert.NotContains(t, thinking, "budget_tokens")++ outputConfig := payload["output_config"].(map[string]any)+ assert.Equal(t, "xhigh", outputConfig["effort"])++ // Opus 4.7+ reject sampling params (top-level in the Anthropic Messages API).+ assert.NotContains(t, payload, "temperature")+ assert.NotContains(t, payload, "top_p")+ assert.NotContains(t, payload, "top_k")+}++func TestRewriteAdaptiveThinkingBodyWithoutThinking(t *testing.T) {+ body := []byte(`{"model":"claude-opus-4-6","max_tokens":1024}`)++ updatedBody, err := rewriteAdaptiveThinkingBody(body, "high")+ require.NoError(t, err)+ assert.JSONEq(t, string(body), string(updatedBody))+}++// TestAdaptiveThinkingRoundTrip verifies the full local chain (adaptive-only model+// -> prepareCallOptions -> ctx -> langchaingo -> RoundTripper rewrite) by capturing+// the request that actually hits the wire, without needing a real API call.+func TestAdaptiveThinkingRoundTrip(t *testing.T) {+ var (+ mu sync.Mutex+ captured []byte+ )+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ body, _ := io.ReadAll(r.Body)+ mu.Lock()+ captured = body+ mu.Unlock()+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`{"id":"msg_1","type":"message","role":"assistant","model":"claude-opus-4-8","content":[{"type":"text","text":"ok"}],"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}`))+ }))+ defer server.Close()++ // simple -> claude-opus-4-8 (adaptive-only in models.yml) with temperature set,+ // so the backstop must force adaptive and the rewrite must strip temperature.+ providerConfig, err := BuildProviderConfig([]byte("simple:\n model: claude-opus-4-8\n temperature: 1.0\n n: 1\n max_tokens: 1000\n"))+ require.NoError(t, err)++ cfg := &config.Config{AnthropicAPIKey: "test-key", AnthropicServerURL: server.URL}+ prov, err := New(cfg, provider.DefaultProviderNameAnthropic, providerConfig)+ require.NoError(t, err)++ // The response is a stub; we only assert on the captured request body.+ _, _ = prov.Call(context.Background(), pconfig.OptionsTypeSimple, "hi")++ mu.Lock()+ body := captured+ mu.Unlock()+ require.NotEmpty(t, body, "no request reached the server")++ var payload map[string]any+ require.NoError(t, json.Unmarshal(body, &payload))++ thinking, ok := payload["thinking"].(map[string]any)+ require.True(t, ok, "request must carry a thinking block")+ assert.Equal(t, "adaptive", thinking["type"])+ assert.Equal(t, "summarized", thinking["display"])+ assert.NotContains(t, payload, "temperature", "sampling params must be stripped for adaptive models")+ if oc, ok := payload["output_config"].(map[string]any); ok {+ assert.Equal(t, "high", oc["effort"])+ } else {+ t.Error("request must carry output_config.effort")+ }+}diff --git a/backend/pkg/providers/anthropic/anthropic.go b/backend/pkg/providers/anthropic/anthropic.goindex 914901b2..00d72beb 100644--- a/backend/pkg/providers/anthropic/anthropic.go+++ b/backend/pkg/providers/anthropic/anthropic.go@@ -3,6 +3,7 @@ package anthropicimport ("context""embed"+ "net/http""pentagi/pkg/config""pentagi/pkg/providers/pconfig"@@ -74,6 +75,12 @@ func New(return nil, err}+ base := httpClient.Transport+ if base == nil {+ base = http.DefaultTransport+ }+ httpClient.Transport = &adaptiveThinkingTransport{base: base}+models, err := DefaultModels()if err != nil {return nil, err@@ -148,9 +155,10 @@ func (p *anthropicProvider) Call(opt pconfig.ProviderOptionsType,prompt string,) (string, error) {+ ctx, options := p.prepareCallOptions(ctx, opt, p.providerConfig.GetOptionsForType(opt))return provider.WrapGenerateFromSinglePrompt(ctx, p, opt, p.llm, prompt,- p.providerConfig.GetOptionsForType(opt)...,+ options...,)}@@ -160,11 +168,12 @@ func (p *anthropicProvider) CallEx(chain []llms.MessageContent,streamCb streaming.Callback,) (*llms.ContentResponse, error) {+ ctx, options := p.prepareCallOptions(ctx, opt, append([]llms.CallOption{+ llms.WithStreamingFunc(streamCb),+ }, p.providerConfig.GetOptionsForType(opt)...))return provider.WrapGenerateContent(ctx, p, opt, p.llm.GenerateContent, chain,- append([]llms.CallOption{- llms.WithStreamingFunc(streamCb),- }, p.providerConfig.GetOptionsForType(opt)...)...,+ options...,)}@@ -175,12 +184,13 @@ func (p *anthropicProvider) CallWithTools(tools []llms.Tool,streamCb streaming.Callback,) (*llms.ContentResponse, error) {+ ctx, options := p.prepareCallOptions(ctx, opt, append([]llms.CallOption{+ llms.WithTools(tools),+ llms.WithStreamingFunc(streamCb),+ }, p.providerConfig.GetOptionsForType(opt)...))return provider.WrapGenerateContent(ctx, p, opt, p.llm.GenerateContent, chain,- append([]llms.CallOption{- llms.WithTools(tools),- llms.WithStreamingFunc(streamCb),- }, p.providerConfig.GetOptionsForType(opt)...)...,+ options...,)}diff --git a/backend/pkg/providers/anthropic/models.yml b/backend/pkg/providers/anthropic/models.ymlindex 19de257f..d26528d5 100644--- a/backend/pkg/providers/anthropic/models.yml+++ b/backend/pkg/providers/anthropic/models.yml@@ -12,6 +12,9 @@- name: claude-sonnet-4-6description: Best combination of speed and intelligence with adaptive thinking support. Exceptional for balanced penetration testing workflows requiring both rapid execution and sophisticated reasoning. Optimized for multi-phase security assessments, intelligent vulnerability analysis, and real-time threat hunting with advanced tool coordination.thinking: true+ reasoning:+ mode: adaptive+ efforts: [low, medium, high, max]release_date: 2026-02-17price:input: 3.0@@ -22,6 +25,9 @@- name: claude-opus-4-6description: The most intelligent model for building autonomous agents and advanced coding. Unmatched capabilities in complex exploit development, sophisticated penetration testing automation, multi-stage attack simulation, and intelligent security research. Features extended and adaptive thinking for maximum reasoning depth in critical security operations.thinking: true+ reasoning:+ mode: adaptive+ efforts: [low, medium, high, max]release_date: 2026-02-05price:input: 5.0@@ -29,6 +35,32 @@cache_read: 0.5cache_write: 6.25+- name: claude-opus-4-8+ description: Anthropic Opus 4.8 - flagship model for coding, agents, and deep reasoning in enterprise security workflows. Adaptive thinking only (manual budget thinking is rejected); sampling parameters are not supported.+ thinking: true+ reasoning:+ mode: adaptive-only+ efforts: [low, medium, high, xhigh, max]+ release_date: 2026-05-28+ price:+ input: 5.0+ output: 25.0+ cache_read: 0.5+ cache_write: 6.25++- name: claude-opus-4-7+ description: Anthropic Opus 4.7 for advanced software engineering, long-running agentic tasks, and rigorous security analysis. Adaptive thinking only (manual budget thinking is rejected); sampling parameters are not supported.+ thinking: true+ reasoning:+ mode: adaptive-only+ efforts: [low, medium, high, xhigh, max]+ release_date: 2026-04-16+ price:+ input: 5.0+ output: 25.0+ cache_read: 0.5+ cache_write: 6.25+# Legacy models - Still supported but consider migrating to newer versions- name: claude-sonnet-4-5description: State-of-the-art reasoning model with superior analytical depth and enhanced tool integration (superseded by sonnet-4-6). Premier choice for sophisticated penetration testing, advanced threat analysis, complex exploit development, and autonomous security research requiring deep reasoning and precise tool orchestration.