Class: ConsoleAgent::ConversationEngine
- Inherits:
-
Object
- Object
- ConsoleAgent::ConversationEngine
- Defined in:
- lib/console_agent/conversation_engine.rb
Constant Summary collapse
- RECENT_OUTPUTS_TO_KEEP =
2
Instance Attribute Summary collapse
-
#history ⇒ Object
readonly
Returns the value of attribute history.
-
#interactive_session_id ⇒ Object
readonly
Returns the value of attribute interactive_session_id.
-
#session_name ⇒ Object
readonly
Returns the value of attribute session_name.
-
#total_input_tokens ⇒ Object
readonly
Returns the value of attribute total_input_tokens.
-
#total_output_tokens ⇒ Object
readonly
Returns the value of attribute total_output_tokens.
Instance Method Summary collapse
- #add_user_message(text) ⇒ Object
- #compact_history ⇒ Object
- #context ⇒ Object
- #display_conversation ⇒ Object
- #display_cost_summary ⇒ Object
-
#display_session_summary ⇒ Object
— Display helpers (used by Channel::Console slash commands) —.
- #execute_direct(raw_code) ⇒ Object
- #explain(query) ⇒ Object
- #finish_interactive_session ⇒ Object
- #init_guide ⇒ Object
-
#init_interactive ⇒ Object
— Interactive session management —.
-
#initialize(binding_context:, channel:, slack_thread_ts: nil) ⇒ ConversationEngine
constructor
A new instance of ConversationEngine.
-
#log_interactive_turn ⇒ Object
— Session logging —.
-
#one_shot(query) ⇒ Object
— Public API for channels —.
- #pop_last_message ⇒ Object
- #process_message(text) ⇒ Object
- #restore_session(session) ⇒ Object
- #send_and_execute ⇒ Object
- #set_interactive_query(text) ⇒ Object
- #set_session_name(name) ⇒ Object
- #upgrade_to_thinking_model ⇒ Object
- #warn_if_history_large ⇒ Object
Constructor Details
#initialize(binding_context:, channel:, slack_thread_ts: nil) ⇒ ConversationEngine
Returns a new instance of ConversationEngine.
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
# File 'lib/console_agent/conversation_engine.rb', line 8 def initialize(binding_context:, channel:, slack_thread_ts: nil) @binding_context = binding_context @channel = channel @slack_thread_ts = slack_thread_ts @executor = Executor.new(binding_context, channel: channel) @provider = nil @context_builder = nil @context = nil @history = [] @total_input_tokens = 0 @total_output_tokens = 0 @token_usage = Hash.new { |h, k| h[k] = { input: 0, output: 0 } } @interactive_session_id = nil @session_name = nil @interactive_query = nil @interactive_start = nil @last_interactive_code = nil @last_interactive_output = nil @last_interactive_result = nil @last_interactive_executed = false @compact_warned = false @prior_duration_ms = 0 end |
Instance Attribute Details
#history ⇒ Object (readonly)
Returns the value of attribute history.
3 4 5 |
# File 'lib/console_agent/conversation_engine.rb', line 3 def history @history end |
#interactive_session_id ⇒ Object (readonly)
Returns the value of attribute interactive_session_id.
3 4 5 |
# File 'lib/console_agent/conversation_engine.rb', line 3 def interactive_session_id @interactive_session_id end |
#session_name ⇒ Object (readonly)
Returns the value of attribute session_name.
3 4 5 |
# File 'lib/console_agent/conversation_engine.rb', line 3 def session_name @session_name end |
#total_input_tokens ⇒ Object (readonly)
Returns the value of attribute total_input_tokens.
3 4 5 |
# File 'lib/console_agent/conversation_engine.rb', line 3 def total_input_tokens @total_input_tokens end |
#total_output_tokens ⇒ Object (readonly)
Returns the value of attribute total_output_tokens.
3 4 5 |
# File 'lib/console_agent/conversation_engine.rb', line 3 def total_output_tokens @total_output_tokens end |
Instance Method Details
#add_user_message(text) ⇒ Object
208 209 210 |
# File 'lib/console_agent/conversation_engine.rb', line 208 def (text) @history << { role: :user, content: text } end |
#compact_history ⇒ Object
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 |
# File 'lib/console_agent/conversation_engine.rb', line 412 def compact_history if @history.length < 6 $stdout.puts "\e[33m History too short to compact (#{@history.length} messages). Need at least 6.\e[0m" return end before_chars = @history.sum { |m| m[:content].to_s.length } before_count = @history.length executed_code = extract_executed_code(@history) $stdout.puts "\e[2m Compacting #{before_count} messages (~#{format_tokens(before_chars)} chars)...\e[0m" system_prompt = <<~PROMPT You are a conversation summarizer. The user will provide a conversation history from a Rails console AI assistant session. Produce a concise summary that captures: - What the user has been working on and their goals - Key findings and data discovered (include specific values, IDs, record counts) - Current state: what worked, what failed, where things stand - Important variable names, model names, or table names referenced Do NOT include code that was executed — that will be preserved separately. Be concise but preserve all information that would be needed to continue the conversation naturally. Do NOT include any preamble — just output the summary directly. PROMPT history_text = @history.map { |m| "#{m[:role]}: #{m[:content]}" }.join("\n\n") = [{ role: :user, content: "Summarize this conversation history:\n\n#{history_text}" }] begin result = provider.chat(, system_prompt: system_prompt) track_usage(result) summary = result.text.to_s.strip if summary.empty? $stdout.puts "\e[33m Compaction failed: empty summary returned.\e[0m" return end content = "CONVERSATION SUMMARY (compacted):\n#{summary}" unless executed_code.empty? content += "\n\nCODE EXECUTED THIS SESSION (preserved for continuation):\n#{executed_code}" end @history = [{ role: :user, content: content }] @compact_warned = false after_chars = @history.first[:content].length $stdout.puts "\e[36m Compacted: #{before_count} messages -> 1 summary (~#{format_tokens(before_chars)} -> ~#{format_tokens(after_chars)} chars)\e[0m" summary.each_line { |line| $stdout.puts "\e[2m #{line.rstrip}\e[0m" } if !executed_code.empty? $stdout.puts "\e[2m (preserved #{executed_code.scan(/```ruby/).length} executed code block(s))\e[0m" end display_usage(result) rescue => e $stdout.puts "\e[31m Compaction failed: #{e.}\e[0m" end end |
#context ⇒ Object
389 390 391 392 393 394 395 396 |
# File 'lib/console_agent/conversation_engine.rb', line 389 def context base = @context_base ||= context_builder.build parts = [base] parts << safety_context parts << @channel.system_instructions parts << binding_variable_summary parts.compact.join("\n\n") end |
#display_conversation ⇒ Object
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 |
# File 'lib/console_agent/conversation_engine.rb', line 371 def display_conversation stdout = @channel.respond_to?(:real_stdout) ? @channel.real_stdout : $stdout if @history.empty? stdout.puts "\e[2m (no conversation history yet)\e[0m" return end trimmed = trim_old_outputs(@history) stdout.puts "\e[36m Conversation (#{trimmed.length} messages, as sent to LLM):\e[0m" trimmed.each_with_index do |msg, i| role = msg[:role].to_s content = msg[:content].to_s label = role == 'user' ? "\e[33m[user]\e[0m" : "\e[36m[assistant]\e[0m" stdout.puts "#{label} #{content}" stdout.puts if i < trimmed.length - 1 end end |
#display_cost_summary ⇒ Object
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 |
# File 'lib/console_agent/conversation_engine.rb', line 344 def display_cost_summary if @token_usage.empty? $stdout.puts "\e[2m No usage yet.\e[0m" return end total_cost = 0.0 $stdout.puts "\e[36m Cost estimate:\e[0m" @token_usage.each do |model, usage| pricing = Configuration::PRICING[model] pricing ||= { input: 0.0, output: 0.0 } if ConsoleAgent.configuration.provider == :local input_str = "in: #{format_tokens(usage[:input])}" output_str = "out: #{format_tokens(usage[:output])}" if pricing cost = (usage[:input] * pricing[:input]) + (usage[:output] * pricing[:output]) total_cost += cost $stdout.puts "\e[2m #{model}: #{input_str} #{output_str} ~$#{'%.2f' % cost}\e[0m" else $stdout.puts "\e[2m #{model}: #{input_str} #{output_str} (pricing unknown)\e[0m" end end $stdout.puts "\e[36m Total: ~$#{'%.2f' % total_cost}\e[0m" end |
#display_session_summary ⇒ Object
— Display helpers (used by Channel::Console slash commands) —
339 340 341 342 |
# File 'lib/console_agent/conversation_engine.rb', line 339 def display_session_summary return if @total_input_tokens == 0 && @total_output_tokens == 0 $stdout.puts "\e[2m[session totals — in: #{@total_input_tokens} | out: #{@total_output_tokens} | total: #{@total_input_tokens + @total_output_tokens}]\e[0m" end |
#execute_direct(raw_code) ⇒ Object
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 |
# File 'lib/console_agent/conversation_engine.rb', line 224 def execute_direct(raw_code) exec_result = @executor.execute(raw_code) output_parts = [] output_parts << "Output:\n#{@executor.last_output.strip}" if @executor.last_output && !@executor.last_output.strip.empty? output_parts << "Return value: #{exec_result.inspect}" if exec_result result_str = output_parts.join("\n\n") result_str = result_str[0..1000] + '...' if result_str.length > 1000 context_msg = "User directly executed code: `#{raw_code}`" context_msg += "\n#{result_str}" unless output_parts.empty? output_id = output_parts.empty? ? nil : @executor.store_output(result_str) @history << { role: :user, content: context_msg, output_id: output_id } @interactive_query ||= "> #{raw_code}" @last_interactive_code = raw_code @last_interactive_output = @executor.last_output @last_interactive_result = exec_result ? exec_result.inspect : nil @last_interactive_executed = true end |
#explain(query) ⇒ Object
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 |
# File 'lib/console_agent/conversation_engine.rb', line 75 def explain(query) start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC) console_capture = StringIO.new with_console_capture(console_capture) do result, _ = send_query(query) track_usage(result) @executor.display_response(result.text) display_usage(result) @_last_log_attrs = { query: query, conversation: [{ role: :user, content: query }, { role: :assistant, content: result.text }], mode: 'explain', executed: false, start_time: start_time } end log_session(@_last_log_attrs.merge(console_output: console_capture.string)) nil rescue Providers::ProviderError => e @channel.display_error("ConsoleAgent Error: #{e.}") nil rescue => e @channel.display_error("ConsoleAgent Error: #{e.class}: #{e.}") nil end |
#finish_interactive_session ⇒ Object
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 |
# File 'lib/console_agent/conversation_engine.rb', line 512 def finish_interactive_session @executor.on_prompt = nil require 'console_agent/session_logger' duration_ms = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - @interactive_start) * 1000).round + @prior_duration_ms if @interactive_session_id SessionLogger.update(@interactive_session_id, conversation: @history, input_tokens: @total_input_tokens, output_tokens: @total_output_tokens, code_executed: @last_interactive_code, code_output: @last_interactive_output, code_result: @last_interactive_result, executed: @last_interactive_executed, console_output: @channel.respond_to?(:console_capture_string) ? @channel.console_capture_string : nil, duration_ms: duration_ms ) elsif @interactive_query log_attrs = { query: @interactive_query, conversation: @history, mode: @slack_thread_ts ? 'slack' : 'interactive', code_executed: @last_interactive_code, code_output: @last_interactive_output, code_result: @last_interactive_result, executed: @last_interactive_executed, console_output: @channel.respond_to?(:console_capture_string) ? @channel.console_capture_string : nil, start_time: @interactive_start } log_attrs[:slack_thread_ts] = @slack_thread_ts if @slack_thread_ts if @channel.user_identity log_attrs[:user_name] = @channel.mode == 'slack' ? "slack:#{@channel.user_identity}" : @channel.user_identity end log_session(log_attrs) end end |
#init_guide ⇒ Object
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 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 |
# File 'lib/console_agent/conversation_engine.rb', line 117 def init_guide storage = ConsoleAgent.storage existing_guide = begin content = storage.read(ConsoleAgent::GUIDE_KEY) (content && !content.strip.empty?) ? content.strip : nil rescue nil end if existing_guide @channel.display(" Existing guide found (#{existing_guide.length} chars). Will update.") else @channel.display(" No existing guide. Exploring the app...") end require 'console_agent/tools/registry' init_tools = Tools::Registry.new(mode: :init) sys_prompt = init_system_prompt(existing_guide) = [{ role: :user, content: "Explore this Rails application and generate the application guide." }] original_timeout = ConsoleAgent.configuration.timeout ConsoleAgent.configuration.timeout = [original_timeout, 120].max result, _ = send_query_with_tools(, system_prompt: sys_prompt, tools_override: init_tools) guide_text = result.text.to_s.strip guide_text = guide_text.sub(/\A```(?:markdown)?\s*\n?/, '').sub(/\n?```\s*\z/, '') guide_text = guide_text.sub(/\A.*?(?=^#\s)/m, '') if guide_text =~ /^#\s/m if guide_text.empty? @channel.display_warning(" No guide content generated.") return nil end storage.write(ConsoleAgent::GUIDE_KEY, guide_text) path = storage.respond_to?(:root_path) ? File.join(storage.root_path, ConsoleAgent::GUIDE_KEY) : ConsoleAgent::GUIDE_KEY $stdout.puts "\e[32m Guide saved to #{path} (#{guide_text.length} chars)\e[0m" display_usage(result) nil rescue Interrupt $stdout.puts "\n\e[33m Interrupted.\e[0m" nil rescue Providers::ProviderError => e @channel.display_error("ConsoleAgent Error: #{e.}") nil rescue => e @channel.display_error("ConsoleAgent Error: #{e.class}: #{e.}") nil ensure ConsoleAgent.configuration.timeout = original_timeout if original_timeout end |
#init_interactive ⇒ Object
— Interactive session management —
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 |
# File 'lib/console_agent/conversation_engine.rb', line 171 def init_interactive @interactive_start = Process.clock_gettime(Process::CLOCK_MONOTONIC) @executor.on_prompt = -> { log_interactive_turn } @history = [] @total_input_tokens = 0 @total_output_tokens = 0 @token_usage = Hash.new { |h, k| h[k] = { input: 0, output: 0 } } @interactive_query = nil @interactive_session_id = nil @session_name = nil @last_interactive_code = nil @last_interactive_output = nil @last_interactive_result = nil @last_interactive_executed = false @compact_warned = false @prior_duration_ms = 0 end |
#log_interactive_turn ⇒ Object
— Session logging —
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 |
# File 'lib/console_agent/conversation_engine.rb', line 483 def log_interactive_turn require 'console_agent/session_logger' session_attrs = { conversation: @history, input_tokens: @total_input_tokens, output_tokens: @total_output_tokens, code_executed: @last_interactive_code, code_output: @last_interactive_output, code_result: @last_interactive_result, executed: @last_interactive_executed, console_output: @channel.respond_to?(:console_capture_string) ? @channel.console_capture_string : nil } if @interactive_session_id SessionLogger.update(@interactive_session_id, session_attrs) else log_attrs = session_attrs.merge( query: @interactive_query || '(interactive session)', mode: @slack_thread_ts ? 'slack' : 'interactive', name: @session_name ) log_attrs[:slack_thread_ts] = @slack_thread_ts if @slack_thread_ts if @channel.user_identity log_attrs[:user_name] = @channel.mode == 'slack' ? "slack:#{@channel.user_identity}" : @channel.user_identity end @interactive_session_id = SessionLogger.log(log_attrs) end end |
#one_shot(query) ⇒ Object
— Public API for channels —
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
# File 'lib/console_agent/conversation_engine.rb', line 34 def one_shot(query) start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC) console_capture = StringIO.new exec_result = with_console_capture(console_capture) do conversation = [{ role: :user, content: query }] exec_result, code, executed = one_shot_round(conversation) if executed && @executor.last_error && !@executor.last_safety_error error_msg = "Code execution failed with error: #{@executor.last_error}" error_msg = error_msg[0..1000] + '...' if error_msg.length > 1000 conversation << { role: :assistant, content: @_last_result_text } conversation << { role: :user, content: error_msg } @channel.display_dim(" Attempting to fix...") exec_result, code, executed = one_shot_round(conversation) end @_last_log_attrs = { query: query, conversation: conversation, mode: 'one_shot', code_executed: code, code_output: executed ? @executor.last_output : nil, code_result: executed && exec_result ? exec_result.inspect : nil, executed: executed, start_time: start_time } exec_result end log_session(@_last_log_attrs.merge(console_output: console_capture.string)) exec_result rescue Providers::ProviderError => e @channel.display_error("ConsoleAgent Error: #{e.}") nil rescue => e @channel.display_error("ConsoleAgent Error: #{e.class}: #{e.}") nil end |
#pop_last_message ⇒ Object
212 213 214 |
# File 'lib/console_agent/conversation_engine.rb', line 212 def @history.pop end |
#process_message(text) ⇒ Object
103 104 105 106 107 108 109 110 111 112 113 114 115 |
# File 'lib/console_agent/conversation_engine.rb', line 103 def (text) # Initialize interactive state if not already set (first message in session) init_interactive unless @interactive_start @channel.log_input(text) if @channel.respond_to?(:log_input) @interactive_query ||= text @history << { role: :user, content: text } status = send_and_execute if status == :error @channel.display_dim(" Attempting to fix...") send_and_execute end end |
#restore_session(session) ⇒ Object
189 190 191 192 193 194 195 196 197 198 199 200 201 202 |
# File 'lib/console_agent/conversation_engine.rb', line 189 def restore_session(session) @history = JSON.parse(session.conversation, symbolize_names: true) @interactive_session_id = session.id @interactive_query = session.query @session_name = session.name @total_input_tokens = session.input_tokens || 0 @total_output_tokens = session.output_tokens || 0 @prior_duration_ms = session.duration_ms || 0 if session.model && (session.input_tokens.to_i > 0 || session.output_tokens.to_i > 0) @token_usage[session.model][:input] = session.input_tokens.to_i @token_usage[session.model][:output] = session.output_tokens.to_i end end |
#send_and_execute ⇒ Object
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 |
# File 'lib/console_agent/conversation_engine.rb', line 246 def send_and_execute begin result, = send_query(nil, conversation: @history) rescue Providers::ProviderError => e if e..include?("prompt is too long") && @history.length >= 6 @channel.display_warning(" Context limit reached. Run /compact to reduce context size, then try again.") else @channel.display_error("ConsoleAgent Error: #{e.class}: #{e.}") end return :error rescue Interrupt $stdout.puts "\n\e[33m Aborted.\e[0m" return :interrupted end track_usage(result) return :cancelled if @channel.cancelled? code = @executor.display_response(result.text) display_usage(result, show_session: true) log_interactive_turn @history.concat() if && !.empty? @history << { role: :assistant, content: result.text } return :no_code unless code && !code.strip.empty? return :cancelled if @channel.cancelled? exec_result = if ConsoleAgent.configuration.auto_execute @executor.execute(code) else @executor.confirm_and_execute(code) end unless @executor.last_cancelled? @last_interactive_code = code @last_interactive_output = @executor.last_output @last_interactive_result = exec_result ? exec_result.inspect : nil @last_interactive_executed = true end if @executor.last_cancelled? @history << { role: :user, content: "User declined to execute the code." } :cancelled elsif @executor.last_safety_error exec_result = @executor.offer_danger_retry(code) if exec_result || !@executor.last_error @last_interactive_code = code @last_interactive_output = @executor.last_output @last_interactive_result = exec_result ? exec_result.inspect : nil @last_interactive_executed = true output_parts = [] if @executor.last_output && !@executor.last_output.strip.empty? output_parts << "Output:\n#{@executor.last_output.strip}" end output_parts << "Return value: #{exec_result.inspect}" if exec_result unless output_parts.empty? result_str = output_parts.join("\n\n") result_str = result_str[0..1000] + '...' if result_str.length > 1000 output_id = @executor.store_output(result_str) @history << { role: :user, content: "Code was executed (safety override). #{result_str}", output_id: output_id } end :success else @history << { role: :user, content: "User declined to execute with safe mode disabled." } :cancelled end elsif @executor.last_error error_msg = "Code execution failed with error: #{@executor.last_error}" error_msg = error_msg[0..1000] + '...' if error_msg.length > 1000 @history << { role: :user, content: error_msg } :error else output_parts = [] if @executor.last_output && !@executor.last_output.strip.empty? output_parts << "Output:\n#{@executor.last_output.strip}" end output_parts << "Return value: #{exec_result.inspect}" if exec_result unless output_parts.empty? result_str = output_parts.join("\n\n") result_str = result_str[0..1000] + '...' if result_str.length > 1000 output_id = @executor.store_output(result_str) @history << { role: :user, content: "Code was executed. #{result_str}", output_id: output_id } end :success end end |
#set_interactive_query(text) ⇒ Object
204 205 206 |
# File 'lib/console_agent/conversation_engine.rb', line 204 def set_interactive_query(text) @interactive_query ||= text end |
#set_session_name(name) ⇒ Object
216 217 218 219 220 221 222 |
# File 'lib/console_agent/conversation_engine.rb', line 216 def set_session_name(name) @session_name = name if @interactive_session_id require 'console_agent/session_logger' SessionLogger.update(@interactive_session_id, name: name) end end |
#upgrade_to_thinking_model ⇒ Object
398 399 400 401 402 403 404 405 406 407 408 409 410 |
# File 'lib/console_agent/conversation_engine.rb', line 398 def upgrade_to_thinking_model config = ConsoleAgent.configuration current = config.resolved_model thinking = config.resolved_thinking_model if current == thinking $stdout.puts "\e[36m Already using thinking model (#{current}).\e[0m" else config.model = thinking @provider = nil $stdout.puts "\e[36m Switched to thinking model: #{thinking}\e[0m" end end |
#warn_if_history_large ⇒ Object
472 473 474 475 476 477 478 479 |
# File 'lib/console_agent/conversation_engine.rb', line 472 def warn_if_history_large chars = @history.sum { |m| m[:content].to_s.length } if chars > 50_000 && !@compact_warned @compact_warned = true $stdout.puts "\e[33m Conversation is getting large (~#{format_tokens(chars)} chars). Consider running /compact to reduce context size.\e[0m" end end |