Class: LanguageOperator::Agent::Executor

Inherits:
Object
  • Object
show all
Includes:
Instrumentation, Loggable
Defined in:
lib/language_operator/agent/executor.rb

Overview

Task Executor

Handles autonomous task execution with retry logic and error handling.

Examples:

executor = Executor.new(agent)
executor.execute("Complete the task")

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Loggable

#logger

Constructor Details

#initialize(agent, agent_definition: nil) ⇒ Executor

Initialize the executor

Parameters:



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/language_operator/agent/executor.rb', line 28

def initialize(agent, agent_definition: nil)
  @agent = agent
  @agent_definition = agent_definition
  @iteration_count = 0
  @max_iterations = 100
  @show_full_responses = ENV.fetch('SHOW_FULL_RESPONSES', 'false') == 'true'
  @metrics_tracker = MetricsTracker.new

  # Initialize safety manager from agent definition or environment
  @safety_manager = initialize_safety_manager(agent_definition)

  logger.debug('Executor initialized',
               max_iterations: @max_iterations,
               show_full_responses: @show_full_responses,
               workspace: @agent.workspace_path,
               safety_enabled: @safety_manager&.enabled?)
end

Instance Attribute Details

#agentObject (readonly)

Returns the value of attribute agent.



22
23
24
# File 'lib/language_operator/agent/executor.rb', line 22

def agent
  @agent
end

#iteration_countObject (readonly)

Returns the value of attribute iteration_count.



22
23
24
# File 'lib/language_operator/agent/executor.rb', line 22

def iteration_count
  @iteration_count
end

#metrics_trackerObject (readonly)

Returns the value of attribute metrics_tracker.



22
23
24
# File 'lib/language_operator/agent/executor.rb', line 22

def metrics_tracker
  @metrics_tracker
end

Instance Method Details

#cleanup_connectionsvoid

This method returns an undefined value.

Cleanup executor resources including MCP connections

This method delegates to the agent's connection cleanup to prevent resource leaks when executors are no longer needed.



65
66
67
# File 'lib/language_operator/agent/executor.rb', line 65

def cleanup_connections
  @agent.cleanup_connections if @agent.respond_to?(:cleanup_connections)
end

#execute(task, agent_definition: nil) ⇒ String

Execute a single task

Parameters:

Returns:

  • (String)

    The result



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
# File 'lib/language_operator/agent/executor.rb', line 74

def execute(task, agent_definition: nil)
  with_span('agent.execute_goal', attributes: {
              'agent.goal_description' => task[0...500]
            }) do
    @iteration_count += 1

    # Standard instruction-based execution
    logger.info('Starting iteration',
                iteration: @iteration_count,
                max_iterations: @max_iterations)
    logger.debug('Prompt', prompt: task[0..200])

    # Safety check before request
    if @safety_manager&.enabled?
      # Estimate cost and tokens (rough estimate)
      estimated_tokens = estimate_tokens(task)
      estimated_cost = estimate_cost(estimated_tokens)

      @safety_manager.check_request!(
        message: task,
        estimated_cost: estimated_cost,
        estimated_tokens: estimated_tokens
      )
    end

    logger.info('LLM request')
    result = logger.timed('LLM response received') do
      @agent.send_message(task)
    end

    # Record metrics
    model_id = @agent.config.dig('llm', 'model')
    @metrics_tracker.record_request(result, model_id) if model_id

    # Safety check after response and record spending
    result_text = result.is_a?(String) ? result : result.content
    metrics = @metrics_tracker.cumulative_stats

    if @safety_manager&.enabled?
      @safety_manager.check_response!(result_text)
      @safety_manager.record_request(
        cost: metrics[:estimatedCost],
        tokens: metrics[:totalTokens]
      )
    end

    # Capture thinking blocks before stripping (for observability)
    thinking_blocks = result_text.scan(%r{\[THINK\](.*?)\[/THINK\]}m).flatten
    if thinking_blocks.any?
      logger.info('LLM thinking captured',
                  event: 'llm_thinking',
                  iteration: @iteration_count,
                  thinking_steps: thinking_blocks.length,
                  thinking: thinking_blocks,
                  thinking_preview: thinking_blocks.first&.[](0..500))
    end

    # Log the actual LLM response content (strip [THINK] blocks)
    cleaned_response = result_text.gsub(%r{\[THINK\].*?\[/THINK\]}m, '').strip
    response_preview = cleaned_response.length > 500 ? "#{cleaned_response[0..500]}..." : cleaned_response
    puts "\e[1;35m·\e[0m #{response_preview}" unless response_preview.empty?

    # Log iteration completion with green dot
    puts "\e[1;32m·\e[0m Iteration completed (iteration=#{@iteration_count}, response_length=#{result_text.length}, total_tokens=#{metrics[:totalTokens]}, estimated_cost=$#{metrics[:estimatedCost]})"

    result
  rescue StandardError => e
    handle_error(e)
  end
end

#execute_with_context(instruction:, context: {}) ⇒ String

Execute a task with additional context (for webhooks/HTTP requests)

Parameters:

  • instruction (String)

    The instruction to execute

  • context (Hash) (defaults to: {})

    Additional context (webhook payload, request data, etc.)

Returns:

  • (String)

    The result



51
52
53
54
55
56
57
# File 'lib/language_operator/agent/executor.rb', line 51

def execute_with_context(instruction:, context: {})
  # Build enriched instruction with context
  enriched_instruction = build_instruction_with_context(instruction, context)

  # Execute with standard logic
  execute(enriched_instruction)
end

#run_loopvoid

This method returns an undefined value.

Run continuous execution loop



149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
# File 'lib/language_operator/agent/executor.rb', line 149

def run_loop
  start_time = Time.now

  logger.info('Starting execution')
  logger.info('Configuration',
              workspace: @agent.workspace_path,
              mcp_servers: @agent.servers_info.length,
              max_iterations: @max_iterations)

  # Log persona loading
  persona = @agent.config.dig('agent', 'persona') || 'default'
  logger.info("👤 Loading persona: #{persona}")

  # Log MCP server details
  if @agent.servers_info.any?
    @agent.servers_info.each do |server|
      logger.info('◆ MCP server connected', name: server[:name], tool_count: server[:tool_count])
    end
  end

  # Get initial instructions from config or environment
  instructions = @agent.config.dig('agent', 'instructions') ||
                 ENV['AGENT_INSTRUCTIONS'] ||
                 'Monitor workspace and respond to changes'

  # Log instructions with bold white formatting
  instructions_preview = instructions[0..200]
  puts "\e[1;37m·\e[0m \e[1;37m#{instructions_preview}\e[0m"
  logger.info('Starting autonomous execution loop')

  loop do
    break if @iteration_count >= @max_iterations

    progress_pct = ((@iteration_count.to_f / @max_iterations) * 100).round(1)
    logger.debug('Loop progress',
                 iteration: @iteration_count,
                 max: @max_iterations,
                 progress: "#{progress_pct}%")

    result = execute(instructions)
    result_text = result.is_a?(String) ? result : result.content

    # Log result based on verbosity settings
    if @show_full_responses
      logger.info('Full iteration result',
                  iteration: @iteration_count,
                  result: result_text)
    else
      preview = result_text[0..200]
      preview += '...' if result_text.length > 200
      logger.info('Iteration result',
                  iteration: @iteration_count,
                  preview: preview)
    end

    # Rate limiting
    logger.debug('Rate limit pause', duration: 5)
    sleep 5
  end

  # Log execution summary
  total_duration = Time.now - start_time
  metrics = @metrics_tracker.cumulative_stats
  logger.info('Execution complete',
              iterations: @iteration_count,
              duration_s: total_duration.round(2),
              total_requests: metrics[:requestCount],
              total_tokens: metrics[:totalTokens],
              estimated_cost: "$#{metrics[:estimatedCost]}",
              reason: @iteration_count >= @max_iterations ? 'max_iterations' : 'completed')

  return unless @iteration_count >= @max_iterations

  logger.warn('Maximum iterations reached',
              iterations: @max_iterations,
              reason: 'Hit max_iterations limit')
end