Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

fix: bound denied model tool loops

rcourtmane6d40f3c117b
diff --git a/docs/release-control/v6/internal/status.json b/docs/release-control/v6/internal/status.json
index c2218d59c3..19a5be75e6 100644
--- a/docs/release-control/v6/internal/status.json
+++ b/docs/release-control/v6/internal/status.json
@@ -3989,7 +3989,7 @@
"./internal/ai/tools",
"./internal/api",
"-run",
- "TestParseProviderToolInputRejectsInternalApprovalMetadata|TestValidateDeclaredToolArgumentsRejectsUnknownProviderProperties|TestExecuteCommand_RoundTripViaWebSocket|TestExecuteCommand_InvalidApprovalAuthorizationNeverMintsOrDispatches|TestService_ExecuteStream_AutonomousRawCommandRequiresApproval|TestPulseToolExecutor_ExecuteRunCommand|TestHandleChat_CannotElevateAutonomousModePerRequest|TestVerifyAndConsumeCommandAuthorization",
+ "TestParseProviderToolInputRejectsInternalApprovalMetadata|TestValidateDeclaredToolArgumentsRejectsUnknownProviderProperties|TestExecuteCommand_RoundTripViaWebSocket|TestExecuteCommand_InvalidApprovalAuthorizationNeverMintsOrDispatches|TestService_ExecuteStream_AutonomousRawCommandRequiresApproval|TestService_Execute_RepeatedDeniedToolCallTerminatesBounded|TestServiceToolLoop_|TestPulseToolExecutor_ExecuteRunCommand|TestHandleChat_CannotElevateAutonomousModePerRequest|TestVerifyAndConsumeCommandAuthorization",
"-count=1"
]
},
@@ -4108,6 +4108,17 @@
"path": "internal/ai/chat/service_investigation.go",
"kind": "file"
},
+ {
+ "repo": "pulse",
+ "path": "internal/ai/service_tool_loop.go",
+ "kind": "file"
+ },
+ {
+ "repo": "pulse",
+ "path": "internal/ai/service_tool_loop_test.go",
+ "kind": "file",
+ "evidence_tier": "test-proof"
+ },
{
"repo": "pulse",
"path": "internal/ai/tools/control_run_command_test.go",
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index e77bd197cb..6cb08a12b1 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -44,6 +44,16 @@ side-effect-free typed proposal whose correlation identity is server-authored.
Unknown profiles, actions, aliases, origins, scopes, and mutation
classifications fail closed.
+Model/tool orchestration is bounded by construction rather than by request
+timeout. The legacy `Service` streaming and non-streaming paths share one
+ten-provider-call budget owned by `internal/ai/service_tool_loop.go`; reaching
+that budget returns a typed terminal failure. A provider that repeats the same
+policy-denied tool name and arguments terminates on the second provider call,
+before the repeated call can execute. Denial-loop termination must not create
+an approval, mint command authority, dispatch an agent message, or mutate
+external state. The canonical chat `AgenticLoop` retains its separately
+configurable bounded-turn contract for native Assistant and Patrol flows.
+
Discovery `run` currently persists read-derived evidence in the discovery
cache. That cache write is not an H1 finding/knowledge/infrastructure mutation
exception and remains a separately governed residual under
diff --git a/internal/ai/service.go b/internal/ai/service.go
index d1c4db6a3d..9353b3d774 100644
--- a/internal/ai/service.go
+++ b/internal/ai/service.go
@@ -2247,12 +2247,16 @@ Always execute the commands rather than telling the user how to do it.`
var finalContent string
var model string
- // Agentic loop - keep going while AI requests tools
- maxIterations := 10 // Safety limit
- for i := 0; i < maxIterations; i++ {
+ // Agentic loop - keep going while AI requests tools within the shared
+ // provider-call budget.
+ loopGuard := newServiceToolLoopGuard()
+ for {
if err := s.enforceBudget(req.UseCase); err != nil {
return nil, err
}
+ if err := loopGuard.beforeProviderCall(); err != nil {
+ return nil, err
+ }
chatReq := providers.ChatRequest{
Messages: messages,
@@ -2299,6 +2303,9 @@ Always execute the commands rather than telling the user how to do it.`
if len(resp.ToolCalls) == 0 || resp.StopReason != "tool_use" {
break
}
+ if err := s.observeDeniedServiceToolCalls(loopGuard, resp.ToolCalls); err != nil {
+ return nil, err
+ }
// Add assistant's response with tool calls to messages
messages = append(messages, providers.Message{
@@ -2466,11 +2473,19 @@ Always execute the commands rather than telling the user how to do it.`
var finalContent string
var model string
- // Agentic loop - keep going while AI requests tools
- // No artificial iteration limit - the context timeout (5 minutes) provides the safety net
- iteration := 0
+ // Agentic loop - keep going while AI requests tools within the same
+ // provider-call budget as non-streaming execution.
+ loopGuard := newServiceToolLoopGuard()
for {
- iteration++
+ if err := s.enforceBudget(req.UseCase); err != nil {
+ callback(StreamEvent{Type: "error", Data: map[string]string{"message": err.Error()}})
+ return nil, err
+ }
+ if err := loopGuard.beforeProviderCall(); err != nil {
+ emitServiceToolLoopFailure(callback, err)
+ return nil, err
+ }
+ iteration := loopGuard.providerCalls
log.Debug().
Int("iteration", iteration).
Int("message_count", len(messages)).
@@ -2484,11 +2499,6 @@ Always execute the commands rather than telling the user how to do it.`
callback(StreamEvent{Type: "processing", Data: fmt.Sprintf("Analyzing results (iteration %d)...", iteration)})
}
- if err := s.enforceBudget(req.UseCase); err != nil {
- callback(StreamEvent{Type: "error", Data: map[string]string{"message": err.Error()}})
- return nil, err
- }
-
chatReq := providers.ChatRequest{
Messages: messages,
Model: modelString,
@@ -2564,6 +2574,10 @@ Always execute the commands rather than telling the user how to do it.`
Msg("AI streaming loop ending - no more tool calls or stop_reason != tool_use")
break
}
+ if err := s.observeDeniedServiceToolCalls(loopGuard, resp.ToolCalls); err != nil {
+ emitServiceToolLoopFailure(callback, err)
+ return nil, err
+ }
// Add assistant's response with tool calls to messages
messages = append(messages, providers.Message{
diff --git a/internal/ai/service_extended_test.go b/internal/ai/service_extended_test.go
index e16146a848..858b012c2a 100644
--- a/internal/ai/service_extended_test.go
+++ b/internal/ai/service_extended_test.go
@@ -2112,6 +2112,8 @@ func TestService_ExecuteStream_PolicyBlock(t *testing.T) {
func TestService_ExecuteStream_AutonomousRawCommandRequiresApproval(t *testing.T) {
tmpDir := t.TempDir()
+ store := installEmptyServiceToolLoopApprovalStore(t)
+ mutationPath := filepath.Join(tmpDir, "autonomous-raw-command")
persistence := config.NewConfigPersistence(tmpDir)
dispatches := 0
svc := NewService(persistence, &mockAgentServer{
@@ -2128,8 +2130,8 @@ func TestService_ExecuteStream_AutonomousRawCommandRequiresApproval(t *testing.T
chatFunc: func(ctx context.Context, req providers.ChatRequest) (*providers.ChatResponse, error) {
iteration++
return &providers.ChatResponse{
- ToolCalls: []providers.ToolCall{{ID: "call-1", Name: "run_command", Input: map[string]interface{}{
- "command": "touch /tmp/autonomous-raw-command", "target_host": "agent-1",
+ ToolCalls: []providers.ToolCall{{ID: fmt.Sprintf("call-%d", iteration), Name: "run_command", Input: map[string]interface{}{
+ "command": "touch " + mutationPath, "target_host": "agent-1",
}}},
StopReason: "tool_use",
}, nil
@@ -2138,22 +2140,35 @@ func TestService_ExecuteStream_AutonomousRawCommandRequiresApproval(t *testing.T
svc.provider = mock
approvalEvents := 0
+ loopFailureEvents := 0
_, err := svc.ExecuteStream(context.Background(), ExecuteRequest{TargetType: "agent"}, func(event StreamEvent) {
if event.Type == "approval_needed" {
approvalEvents++
}
+ if event.Type == "error" {
+ if data, ok := event.Data.(ServiceToolLoopFailureData); ok && data.Code == ServiceToolLoopFailureCode {
+ loopFailureEvents++
+ }
+ }
})
- if err != nil {
- t.Fatalf("ExecuteStream failed: %v", err)
- }
+ requireServiceToolLoopFailure(t, err, ServiceToolLoopFailureRepeatedDenied)
if dispatches != 0 {
t.Fatalf("agent dispatches = %d, want 0", dispatches)
}
- if iteration != 1 {
- t.Fatalf("provider iterations = %d, want 1", iteration)
+ if iteration != 2 {
+ t.Fatalf("provider iterations = %d, want 2", iteration)
+ }
+ if approvalEvents != 0 {
+ t.Fatalf("approval events = %d, want 0", approvalEvents)
+ }
+ if loopFailureEvents != 1 {
+ t.Fatalf("typed loop failure events = %d, want 1", loopFailureEvents)
+ }
+ if got := len(store.GetPendingApprovals()); got != 0 {
+ t.Fatalf("persisted approvals = %d, want 0", got)
}
- if approvalEvents != 1 {
- t.Fatalf("approval events = %d, want 1", approvalEvents)
+ if _, statErr := os.Stat(mutationPath); !os.IsNotExist(statErr) {
+ t.Fatalf("external mutation path exists or stat failed unexpectedly: %v", statErr)
}
}
diff --git a/internal/ai/service_tool_loop.go b/internal/ai/service_tool_loop.go
new file mode 100644
index 0000000000..84359ababd
--- /dev/null
+++ b/internal/ai/service_tool_loop.go
@@ -0,0 +1,157 @@
+package ai
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "strings"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/agentcapabilities"
+ "github.com/rcourtman/pulse-go-rewrite/internal/agentexec"
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/providers"
+)
+
+const (
+ // MaxServiceToolIterations is the provider-call budget for the legacy
+ // Service tool loop. Both streaming and non-streaming orchestration consume
+ // this same budget; a request never relies on a wall-clock timeout to stop a
+ // provider that keeps returning tool calls.
+ MaxServiceToolIterations = 10
+
+ ServiceToolLoopFailureCode = "TOOL_LOOP_BOUNDED_FAILURE"
+)
+
+type ServiceToolLoopFailureReason string
+
+const (
+ ServiceToolLoopFailureRepeatedDenied ServiceToolLoopFailureReason = "repeated_denied_tool_call"
+ ServiceToolLoopFailureMaxIterations ServiceToolLoopFailureReason = "max_tool_iterations"
+)
+
+// ServiceToolLoopError is the typed terminal result for a bounded legacy
+// Service model/tool loop. ProviderCalls is the exact number of provider calls
+// already made; no additional provider or tool work occurs after this error.
+type ServiceToolLoopError struct {
+ Reason ServiceToolLoopFailureReason
+ ProviderCalls int
+ MaxProviderCalls int
+ ToolName string
+}
+
+func (e *ServiceToolLoopError) Error() string {
+ if e == nil {
+ return "Pulse Assistant tool loop terminated"
+ }
+ switch e.Reason {
+ case ServiceToolLoopFailureRepeatedDenied:
+ return fmt.Sprintf("Pulse Assistant tool loop terminated after provider repeated denied tool %q (%d provider calls)", e.ToolName, e.ProviderCalls)
+ case ServiceToolLoopFailureMaxIterations:
+ return fmt.Sprintf("Pulse Assistant tool loop reached the maximum of %d provider calls", e.MaxProviderCalls)
+ default:
+ return fmt.Sprintf("Pulse Assistant tool loop terminated after %d provider calls", e.ProviderCalls)
+ }
+}
+
+// ServiceToolLoopFailureData is the stable typed stream projection of
+// ServiceToolLoopError.
+type ServiceToolLoopFailureData struct {
+ Code string `json:"code"`
+ Reason ServiceToolLoopFailureReason `json:"reason"`
+ Message string `json:"message"`
+ ProviderCalls int `json:"provider_calls"`
+ MaxProviderCalls int `json:"max_provider_calls"`
+ ToolName string `json:"tool_name,omitempty"`
+}
+
+func newServiceToolLoopFailureData(err *ServiceToolLoopError) ServiceToolLoopFailureData {
+ return ServiceToolLoopFailureData{
+ Code: ServiceToolLoopFailureCode,
+ Reason: err.Reason,
+ Message: err.Error(),
+ ProviderCalls: err.ProviderCalls,
+ MaxProviderCalls: err.MaxProviderCalls,
+ ToolName: err.ToolName,
+ }
+}
+
+type serviceToolLoopGuard struct {
+ providerCalls int
+ maxCalls int
+ deniedCalls map[string]struct{}
+}
+
+func newServiceToolLoopGuard() *serviceToolLoopGuard {
+ return &serviceToolLoopGuard{
+ maxCalls: MaxServiceToolIterations,
+ deniedCalls: make(map[string]struct{}),
+ }
+}
+
+func (g *serviceToolLoopGuard) beforeProviderCall() error {
+ if g.providerCalls >= g.maxCalls {
+ return &ServiceToolLoopError{
+ Reason: ServiceToolLoopFailureMaxIterations,
+ ProviderCalls: g.providerCalls,
+ MaxProviderCalls: g.maxCalls,
+ }
+ }
+ g.providerCalls++
+ return nil
+}
+
+func (g *serviceToolLoopGuard) observeDeniedToolCall(call providers.ToolCall) error {
+ fingerprint := serviceToolCallFingerprint(call)
+ if _, repeated := g.deniedCalls[fingerprint]; repeated {
+ return &ServiceToolLoopError{
+ Reason: ServiceToolLoopFailureRepeatedDenied,
+ ProviderCalls: g.providerCalls,
+ MaxProviderCalls: g.maxCalls,
+ ToolName: strings.TrimSpace(call.Name),
+ }
+ }
+ g.deniedCalls[fingerprint] = struct{}{}
+ return nil
+}
+
+func serviceToolCallFingerprint(call providers.ToolCall) string {
+ input, err := json.Marshal(call.Input)
+ if err != nil {
+ input = []byte(fmt.Sprintf("%#v", call.Input))
+ }
+ sum := sha256.Sum256(append([]byte(strings.TrimSpace(call.Name)+"\x00"), input...))
+ return hex.EncodeToString(sum[:])
+}
+
+func (s *Service) observeDeniedServiceToolCalls(guard *serviceToolLoopGuard, calls []providers.ToolCall) error {
+ for _, call := range calls {
+ if !s.isDeniedServiceToolCall(call) {
+ continue
+ }
+ if err := guard.observeDeniedToolCall(call); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func (s *Service) isDeniedServiceToolCall(call providers.ToolCall) bool {
+ class := agentcapabilities.ClassifyLegacyAssistantInvocation(call.Name)
+ if !s.legacyAssistantInvocationPolicy().Allows(call.Name, class) {
+ return true
+ }
+ if call.Name != agentcapabilities.LegacyAssistantRunCommandToolName || s.policy == nil {
+ return false
+ }
+ command, _ := call.Input[agentcapabilities.LegacyAssistantCommandArgumentName].(string)
+ return s.policy.Evaluate(command) == agentexec.PolicyBlock
+}
+
+func emitServiceToolLoopFailure(callback StreamCallback, err error) {
+ var loopErr *ServiceToolLoopError
+ if !errors.As(err, &loopErr) || callback == nil {
+ return
+ }
+ callback(StreamEvent{Type: "error", Data: newServiceToolLoopFailureData(loopErr)})
+}
diff --git a/internal/ai/service_tool_loop_test.go b/internal/ai/service_tool_loop_test.go
new file mode 100644
index 0000000000..d20e65f0d9
--- /dev/null
+++ b/internal/ai/service_tool_loop_test.go
@@ -0,0 +1,160 @@
+package ai
+
+import (
+ "context"
+ "errors"
+ "testing"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/agentexec"
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/approval"
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/providers"
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+)
+
+func installEmptyServiceToolLoopApprovalStore(t *testing.T) *approval.Store {
+ t.Helper()
+ store, err := approval.NewStore(approval.StoreConfig{DataDir: t.TempDir(), DisablePersistence: true})
+ if err != nil {
+ t.Fatalf("NewStore: %v", err)
+ }
+ previous := approval.GetStore()
+ approval.SetStore(store)
+ t.Cleanup(func() { approval.SetStore(previous) })
+ return store
+}
+
+func requireServiceToolLoopFailure(t *testing.T, err error, reason ServiceToolLoopFailureReason) *ServiceToolLoopError {
+ t.Helper()
+ var loopErr *ServiceToolLoopError
+ if !errors.As(err, &loopErr) {
+ t.Fatalf("error = %v, want *ServiceToolLoopError", err)
+ }
+ if loopErr.Reason != reason {
+ t.Fatalf("loop failure reason = %q, want %q", loopErr.Reason, reason)
+ }
+ return loopErr
+}
+
+func TestService_Execute_RepeatedDeniedToolCallTerminatesBounded(t *testing.T) {
+ store := installEmptyServiceToolLoopApprovalStore(t)
+ dispatches := 0
+ svc := NewService(config.NewConfigPersistence(t.TempDir()), &mockAgentServer{
+ agents: []agentexec.ConnectedAgent{{AgentID: "agent-1", Hostname: "agent-1"}},
+ executeFunc: func(context.Context, string, agentexec.ExecuteCommandPayload) (*agentexec.CommandResultPayload, error) {
+ dispatches++
+ return &agentexec.CommandResultPayload{Success: true}, nil
+ },
+ })
+ svc.cfg = &config.AIConfig{Enabled: true, ControlLevel: config.ControlLevelAutonomous, Model: "anthropic:test"}
+ providerCalls := 0
+ svc.provider = &mockProvider{chatFunc: func(context.Context, providers.ChatRequest) (*providers.ChatResponse, error) {
+ providerCalls++
+ return &providers.ChatResponse{
+ ToolCalls: []providers.ToolCall{{ID: "changing-id", Name: "run_command", Input: map[string]interface{}{
+ "command": "touch /tmp/must-not-run", "target_host": "agent-1",
+ }}},
+ StopReason: "tool_use",
+ }, nil
+ }}
+
+ _, err := svc.Execute(context.Background(), ExecuteRequest{TargetType: "agent"})
+ loopErr := requireServiceToolLoopFailure(t, err, ServiceToolLoopFailureRepeatedDenied)
+ if providerCalls != 2 || loopErr.ProviderCalls != 2 {
+ t.Fatalf("provider calls = %d error_calls=%d, want 2", providerCalls, loopErr.ProviderCalls)
+ }
+ if dispatches != 0 {
+ t.Fatalf("agent dispatches = %d, want 0", dispatches)
+ }
+ if got := len(store.GetPendingApprovals()); got != 0 {
+ t.Fatalf("persisted approvals = %d, want 0", got)
+ }
+}
+
+func TestServiceToolLoop_MaxIterationsBoundStreamingAndNonStreaming(t *testing.T) {
+ for _, streaming := range []bool{false, true} {
+ name := "non-streaming"
+ if streaming {
+ name = "streaming"
+ }
+ t.Run(name, func(t *testing.T) {
+ store := installEmptyServiceToolLoopApprovalStore(t)
+ svc := NewService(config.NewConfigPersistence(t.TempDir()), nil)
+ svc.cfg = &config.AIConfig{Enabled: true, ControlLevel: config.ControlLevelReadOnly, Model: "anthropic:test"}
+ providerCalls := 0
+ svc.provider = &mockProvider{chatFunc: func(context.Context, providers.ChatRequest) (*providers.ChatResponse, error) {
+ providerCalls++
+ return &providers.ChatResponse{
+ ToolCalls: []providers.ToolCall{{ID: "fetch", Name: "fetch_url", Input: map[string]interface{}{"url": ""}}},
+ StopReason: "tool_use",
+ }, nil
+ }}
+
+ var (
+ err error
+ loopFailureEvents int
+ )
+ if streaming {
+ _, err = svc.ExecuteStream(context.Background(), ExecuteRequest{}, func(event StreamEvent) {
+ if data, ok := event.Data.(ServiceToolLoopFailureData); event.Type == "error" && ok && data.Reason == ServiceToolLoopFailureMaxIterations {
+ loopFailureEvents++
+ }
+ })
+ } else {
+ _, err = svc.Execute(context.Background(), ExecuteRequest{})
+ }
+ loopErr := requireServiceToolLoopFailure(t, err, ServiceToolLoopFailureMaxIterations)
+ if providerCalls != MaxServiceToolIterations || loopErr.ProviderCalls != MaxServiceToolIterations {
+ t.Fatalf("provider calls = %d error_calls=%d, want %d", providerCalls, loopErr.ProviderCalls, MaxServiceToolIterations)
+ }
+ if got := len(store.GetPendingApprovals()); got != 0 {
+ t.Fatalf("persisted approvals = %d, want 0", got)
+ }
+ if streaming && loopFailureEvents != 1 {
+ t.Fatalf("typed max-iteration stream failures = %d, want 1", loopFailureEvents)
+ }
+ })
+ }
+}
+
+func TestServiceToolLoop_AllowsTerminalResponseAtProviderCallBudget(t *testing.T) {
+ for _, streaming := range []bool{false, true} {
+ name := "non-streaming"
+ if streaming {
+ name = "streaming"
+ }
+ t.Run(name, func(t *testing.T) {
+ svc := NewService(config.NewConfigPersistence(t.TempDir()), nil)
+ svc.cfg = &config.AIConfig{Enabled: true, ControlLevel: config.ControlLevelReadOnly, Model: "anthropic:test"}
+ providerCalls := 0
+ svc.provider = &mockProvider{chatFunc: func(context.Context, providers.ChatRequest) (*providers.ChatResponse, error) {
+ providerCalls++
+ if providerCalls == MaxServiceToolIterations {
+ return &providers.ChatResponse{Content: "bounded conversation complete", StopReason: "end_turn"}, nil
+ }
+ return &providers.ChatResponse{
+ ToolCalls: []providers.ToolCall{{ID: "fetch", Name: "fetch_url", Input: map[string]interface{}{"url": ""}}},
+ StopReason: "tool_use",
+ }, nil
+ }}
+
+ var (
+ resp *ExecuteResponse
+ err error
+ )
+ if streaming {
+ resp, err = svc.ExecuteStream(context.Background(), ExecuteRequest{}, func(StreamEvent) {})
+ } else {
+ resp, err = svc.Execute(context.Background(), ExecuteRequest{})
+ }
+ if err != nil {
+ t.Fatalf("bounded conversation failed: %v", err)
+ }
+ if providerCalls != MaxServiceToolIterations {
+ t.Fatalf("provider calls = %d, want %d", providerCalls, MaxServiceToolIterations)
+ }
+ if resp == nil || resp.Content != "bounded conversation complete" {
+ t.Fatalf("response = %#v, want terminal bounded content", resp)
+ }
+ })
+ }
+}