Class: Brute::Middleware::DoomLoopDetection

Inherits:
Base
  • Object
show all
Defined in:
lib/brute/middleware/doom_loop_detection.rb

Overview

Detects when the agent is stuck repeating tool call patterns and injects a corrective warning into the message history before the next LLM call.

Runs PRE-call: inspects the conversation history for repeating tool call patterns. If detected, appends a warning message so the LLM sees it as input alongside the normal tool results.

Instance Method Summary collapse

Constructor Details

#initialize(app, threshold: 3) ⇒ DoomLoopDetection

Returns a new instance of DoomLoopDetection.



16
17
18
19
# File 'lib/brute/middleware/doom_loop_detection.rb', line 16

def initialize(app, threshold: 3)
  super(app)
  @detector = Brute::Loop::DoomLoopDetector.new(threshold: threshold)
end

Instance Method Details

#call(env) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/brute/middleware/doom_loop_detection.rb', line 21

def call(env)
  messages = env[:messages]

  if (reps = @detector.detect(messages))
    warning = @detector.warning_message(reps)
    # Inject the warning as a user message so the LLM sees it
    env[:messages] << LLM::Message.new(:user, warning)
    env[:metadata][:doom_loop_detected] = reps

    # Signal the agent loop to exit after this LLM call completes.
    # First-writer-wins: don't overwrite if another middleware already set it.
    env[:should_exit] ||= {
      reason:  "doom_loop_detected",
      message: "Agent is stuck repeating the same tool calls (#{reps} repetitions).",
      source:  "DoomLoopDetection",
    }
  end

  @app.call(env)
end