Class: Brute::Middleware::Loop

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

Overview

Re-invokes the inner stack as long as a condition holds — a generic loop over a turn. The condition is a proc or block that receives env and returns truthy to send control back down the chain again, falsy to stop.

The inner app always runs at least once; the condition is checked after each pass (do-while).

# loop while the last message is a tool result (see Loop::ToolResult):
use Brute::Middleware::Loop, ->(env) { env[:messages].last&.role == :tool }

# block form — e.g. bump an iteration counter and stop on should_exit:
use Brute::Middleware::Loop do |env|
env[:current_iteration] += 1
!env[:should_exit] && env[:messages].last&.role == :tool
end

Defined Under Namespace

Classes: BackgroundJobs, ToolResult

Constant Summary

Constants included from Hooks

Hooks::AFTER_LLM_EVENT, Hooks::AFTER_TOOL_EVENT, Hooks::APPROVE_TOOL_EVENT, Hooks::BEFORE_LLM_EVENT, Hooks::BEFORE_TOOL_EVENT, Hooks::COMPACTED_EVENT, Hooks::COMPACT_DURATION_EVENT, Hooks::DURATION_EVENT, Hooks::ENTER_EVENT, Hooks::EXIT_EVENT, Hooks::FARADAY_ERROR_EVENT, Hooks::LLM_DURATION_EVENT, Hooks::LLM_FAILURE_EVENT, Hooks::MIDDLEWARE_ADDED_EVENT, Hooks::OPEN_ROUTER_SERVER_ERROR_EVENT, Hooks::STANDARD_ERROR_EVENT, Hooks::TOOL_DURATION_EVENT, Hooks::TURN_DURATION_EVENT, Hooks::TURN_END_EVENT, Hooks::TURN_START_EVENT

Instance Method Summary collapse

Methods included from Hooks

new

Constructor Details

#initialize(app, condition = nil, &block) ⇒ Loop

Returns a new instance of Loop.



25
26
27
28
29
30
31
32
# File 'lib/brute/middleware/006_loop.rb', line 25

def initialize(app, condition = nil, &block)
  @app       = app
  @condition = condition || block

  unless @condition.respond_to?(:call)
    raise ArgumentError, "Brute::Middleware::Loop requires a proc or block condition"
  end
end

Instance Method Details

#call(env) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
# File 'lib/brute/middleware/006_loop.rb', line 34

def call(env)
  loop do
    @app.call(env)

    unless @condition.call(env)
      break
    end
  end

  env
end