Module: Clacky::Agent::MessageCompressorHelper
- Included in:
- Clacky::Agent
- Defined in:
- lib/clacky/agent/message_compressor_helper.rb
Overview
Message compression functionality for managing conversation history Handles automatic compression when token limits are exceeded
Constant Summary collapse
- COMPRESSION_THRESHOLD =
Compression thresholds
150_000- MESSAGE_COUNT_THRESHOLD =
Trigger compression when exceeding this (in tokens)
200- MAX_RECENT_MESSAGES =
Trigger compression when exceeding this (in message count)
20- TARGET_COMPRESSED_TOKENS =
Keep this many recent message pairs intact
10_000- IDLE_COMPRESSION_THRESHOLD =
Target size after compression
20_000
Instance Method Summary collapse
-
#build_chunk_md(messages, chunk_index:, compression_level:) ⇒ String
Build markdown content from a list of messages.
-
#calculate_target_recent_count(reduction_needed) ⇒ Object
Calculate how many recent messages to keep based on how much we need to compress.
-
#compress_messages_if_needed(force: false) ⇒ Hash?
Check if compression is needed and return compression context.
-
#empty_extraction_data ⇒ Object
Helper: empty extraction data.
-
#extract_decision_text(content) ⇒ Object
Helper: extract decision text from content (returns array of decisions or empty array).
-
#extract_from_messages(messages, role_filter = nil, &block) ⇒ Object
Helper: safely extract from messages with proper nil handling.
-
#extract_key_information(messages) ⇒ Object
Extract key information from messages for summarization.
-
#extract_tool_names(tool_calls) ⇒ Object
Helper: extract tool names from tool_calls.
-
#filter_todo_results(result, status) ⇒ Object
Helper: filter todo results by status.
-
#filter_write_results(result, action) ⇒ Object
Helper: filter write results by action.
-
#find_in_progress(messages) ⇒ Object
Helper: find in-progress task.
-
#format_message_content(content) ⇒ Object
Format message content (handles string or array of content blocks).
-
#generate_hierarchical_summary(messages) ⇒ Object
Generate hierarchical summary based on compression level Level 1: Detailed summary with files, decisions, features Level 2: Concise summary with key items Level 3: Minimal summary (just project type) Level 4+: Ultra-minimal (single line).
-
#generate_level1_summary(data) ⇒ Object
Level 1: Detailed summary (for first compression).
-
#generate_level2_summary(data) ⇒ Object
Level 2: Concise summary (for second compression).
-
#generate_level3_summary(data) ⇒ Object
Level 3: Minimal summary (for third compression).
-
#generate_level4_summary(data) ⇒ Object
Level 4: Ultra-minimal summary (for fourth+ compression).
-
#get_recent_messages_with_tool_pairs(messages, count) ⇒ Array
Get recent messages while preserving tool_calls/tool_results pairs.
-
#handle_compression_response(response, compression_context) ⇒ Object
Handle compression response and rebuild message list.
- #parse_shell_result(content) ⇒ Object
- #parse_todo_result(content) ⇒ Object
- #parse_write_result(content) ⇒ Object
-
#pull_assistant_before(messages, tool_result_idx, include_set) ⇒ Object
Walk backwards from tool_result_idx to find and mark its assistant message.
-
#pull_tool_results_after(messages, assistant_idx, include_set) ⇒ Object
Mark all tool results immediately following messages.
-
#save_compressed_chunk(original_messages, recent_messages, chunk_index:, compression_level:) ⇒ String?
Save the messages being compressed to a chunk MD file for future recall File path: ~/.clacky/sessions/datetime-short_id-chunk-n.md.
-
#tool_result_for?(msg, call_ids) ⇒ Boolean
Returns true if msg is a tool result that matches any of the given call IDs.
-
#tool_result_ids(msg) ⇒ Object
Returns the tool_call IDs referenced in a tool result message.
-
#tool_result_message?(msg) ⇒ Boolean
Returns true if msg is a tool result, regardless of storage format.
-
#trigger_idle_compression ⇒ Object
Trigger compression during idle time (user-friendly, interruptible) Returns true if compression was performed, false otherwise.
-
#truncate_content(text, max_length: 500) ⇒ Object
Truncate long content with a note.
-
#truncate_tool_result(msg) ⇒ Object
Truncate oversized tool result content to avoid token bloat.
Instance Method Details
#build_chunk_md(messages, chunk_index:, compression_level:) ⇒ String
Build markdown content from a list of messages
343 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 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 |
# File 'lib/clacky/agent/message_compressor_helper.rb', line 343 def build_chunk_md(, chunk_index:, compression_level:) lines = [] # Front matter lines << "---" lines << "session_id: #{@session_id}" lines << "chunk: #{chunk_index}" lines << "compression_level: #{compression_level}" lines << "archived_at: #{Time.now.iso8601}" lines << "message_count: #{.size}" lines << "---" lines << "" lines << "# Session Chunk #{chunk_index}" lines << "" lines << "> This file contains the original conversation archived during compression." lines << "> Use `file_reader` to recall specific details from this conversation." lines << "" .each do |msg| role = msg[:role] content = msg[:content] case role when "user" lines << "## User" lines << "" lines << (content) lines << "" when "assistant" # If this message is itself a compressed summary, annotate the header # so the reader knows the original conversation is in the referenced chunk if msg[:compressed_summary] && msg[:chunk_path] prev_chunk = File.basename(msg[:chunk_path]) lines << "## Assistant [Compressed Summary — original conversation at: #{prev_chunk}]" else lines << "## Assistant" end lines << "" # Include tool calls summary if present # Format: "_Tool calls: name | {args_json}_" so replay can restore args for WebUI display. if msg[:tool_calls]&.any? tc_parts = msg[:tool_calls].map do |tc| name = tc.dig(:function, :name) || tc[:name] || "" next nil if name.empty? args_raw = tc.dig(:function, :arguments) || tc[:arguments] || {} args = args_raw.is_a?(String) ? (JSON.parse(args_raw) rescue nil) : args_raw if args.is_a?(Hash) && !args.empty? # Truncate large string values to keep chunk MD readable compact = args.transform_values { |v| v.is_a?(String) && v.length > 200 ? v[0..197] + "..." : v } "#{name} | #{compact.to_json}" else name end end.compact lines << "_Tool calls: #{tc_parts.join("; ")}_" lines << "" end lines << (content) if content lines << "" when "tool" tool_name = msg[:name] || "tool" lines << "### Tool Result: #{tool_name}" lines << "" lines << "```" lines << truncate_content(content.to_s, max_length: 500) lines << "```" lines << "" end end lines.join("\n") end |
#calculate_target_recent_count(reduction_needed) ⇒ Object
Calculate how many recent messages to keep based on how much we need to compress
443 444 445 446 447 448 449 450 451 452 453 454 |
# File 'lib/clacky/agent/message_compressor_helper.rb', line 443 def calculate_target_recent_count(reduction_needed) # We want recent messages to be around 20-30% of the total target # This keeps the context window useful without being too large = 500 # Average estimate for a message with content # Target recent messages budget (~20% of target compressed size) recent_budget = (TARGET_COMPRESSED_TOKENS * 0.2).to_i = (recent_budget / ).to_i # Clamp to reasonable bounds [[, 20].max, MAX_RECENT_MESSAGES].min end |
#compress_messages_if_needed(force: false) ⇒ Hash?
Check if compression is needed and return compression context
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 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 |
# File 'lib/clacky/agent/message_compressor_helper.rb', line 57 def (force: false) # Check if compression is enabled return nil unless @config.enable_compression # Use actual API-reported tokens from last request total_tokens = @previous_total_tokens = @history.size # Force compression (for idle compression) - use lower threshold if force # Only compress if we have more than MAX_RECENT_MESSAGES + system message return nil unless > MAX_RECENT_MESSAGES + 1 # Also require minimum message count to make compression worthwhile return nil unless total_tokens >= IDLE_COMPRESSION_THRESHOLD else # Normal compression - check thresholds # Either: token count exceeds threshold OR message count exceeds threshold token_threshold_exceeded = total_tokens >= COMPRESSION_THRESHOLD = >= MESSAGE_COUNT_THRESHOLD # Only compress if we exceed at least one threshold return nil unless token_threshold_exceeded || end # Calculate how much we need to reduce reduction_needed = total_tokens - TARGET_COMPRESSED_TOKENS # Don't compress if reduction is minimal (< 10% of current size) # Only apply this check when triggered by token threshold (not for force mode) if !force && token_threshold_exceeded && reduction_needed < (total_tokens * 0.1) return nil end # If only message count threshold is exceeded, force compression # to keep conversation history manageable # Calculate target size for recent messages based on compression level target_recent_count = calculate_target_recent_count(reduction_needed) # Increment compression level for progressive summarization @compression_level += 1 # Get the most recent N messages, ensuring tool_calls/tool results pairs are kept together = @history.to_a = (, target_recent_count) = [] if .nil? # Build compression instruction message (to be inserted into conversation) = @message_compressor.(, recent_messages: ) return nil if .nil? # Return compression context for agent to handle { compression_message: , recent_messages: , original_token_count: total_tokens, original_message_count: @history.size, compression_level: @compression_level } end |
#empty_extraction_data ⇒ Object
Helper: empty extraction data
574 575 576 577 578 579 580 581 582 583 584 585 586 587 |
# File 'lib/clacky/agent/message_compressor_helper.rb', line 574 def empty_extraction_data { user_msgs: 0, assistant_msgs: 0, tool_msgs: 0, tools_used: [], files_created: [], files_modified: [], decisions: [], completed_tasks: [], in_progress: nil, shell_results: [] } end |
#extract_decision_text(content) ⇒ Object
Helper: extract decision text from content (returns array of decisions or empty array)
547 548 549 550 551 552 553 554 555 556 |
# File 'lib/clacky/agent/message_compressor_helper.rb', line 547 def extract_decision_text(content) return [] unless content.is_a?(String) return [] unless content.include?("decision") || content.include?("chose to") || content.include?("using") sentences = content.split(/[.!?]/).select do |s| s.include?("decision") || s.include?("chose") || s.include?("using") || s.include?("decided") || s.include?("will use") || s.include?("selected") end sentences.map(&:strip).map { |s| s[0..100] } end |
#extract_from_messages(messages, role_filter = nil, &block) ⇒ Object
Helper: safely extract from messages with proper nil handling
518 519 520 521 522 523 524 525 526 527 528 |
# File 'lib/clacky/agent/message_compressor_helper.rb', line 518 def (, role_filter = nil, &block) return [] if .nil? results = .select { |m| role_filter.nil? || m[:role] == role_filter.to_s } .map(&block) .compact # Flatten if we have nested arrays (from methods returning arrays of items) results.any? { |r| r.is_a?(Array) } ? results.flatten.uniq : results.uniq end |
#extract_key_information(messages) ⇒ Object
Extract key information from messages for summarization
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 |
# File 'lib/clacky/agent/message_compressor_helper.rb', line 487 def extract_key_information() return empty_extraction_data if .nil? { # Message counts user_msgs: .count { |m| m[:role] == "user" }, assistant_msgs: .count { |m| m[:role] == "assistant" }, tool_msgs: .count { |m| m[:role] == "tool" }, # Tools used tools_used: (, :assistant) { |m| extract_tool_names(m[:tool_calls]) }, # Files created/modified files_created: (, :tool) { |m| filter_write_results(parse_write_result(m[:content]), :created) }, files_modified: (, :tool) { |m| filter_write_results(parse_write_result(m[:content]), :modified) }, # Key decisions (limit to first 5) decisions: (, :assistant) { |m| extract_decision_text(m[:content]) }.first(5), # Completed tasks (from TODO results) completed_tasks: (, :tool) { |m| filter_todo_results(parse_todo_result(m[:content]), :completed) }, # Current in-progress work in_progress: find_in_progress(), # Key results from shell commands shell_results: (, :tool) { |m| parse_shell_result(m[:content]) } } end |
#extract_tool_names(tool_calls) ⇒ Object
Helper: extract tool names from tool_calls
531 532 533 534 |
# File 'lib/clacky/agent/message_compressor_helper.rb', line 531 def extract_tool_names(tool_calls) return [] unless tool_calls.is_a?(Array) tool_calls.map { |tc| tc.dig(:function, :name) } end |
#filter_todo_results(result, status) ⇒ Object
Helper: filter todo results by status
542 543 544 |
# File 'lib/clacky/agent/message_compressor_helper.rb', line 542 def filter_todo_results(result, status) result && result[:status] == status ? result[:task] : nil end |
#filter_write_results(result, action) ⇒ Object
Helper: filter write results by action
537 538 539 |
# File 'lib/clacky/agent/message_compressor_helper.rb', line 537 def filter_write_results(result, action) result && result[:action] == action ? result[:file] : nil end |
#find_in_progress(messages) ⇒ Object
Helper: find in-progress task
559 560 561 562 563 564 565 566 567 568 569 570 571 |
# File 'lib/clacky/agent/message_compressor_helper.rb', line 559 def find_in_progress() return nil if .nil? .reverse_each do |m| if m[:role] == "tool" content = m[:content].to_s if content.include?("in progress") || content.include?("working on") return content[/[Tt]ODO[:\s]+(.+)/, 1]&.strip || content[/[Ww]orking[Oo]n[:\s]+(.+)/, 1]&.strip end end end nil end |
#format_message_content(content) ⇒ Object
Format message content (handles string or array of content blocks)
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 |
# File 'lib/clacky/agent/message_compressor_helper.rb', line 418 def (content) return "" if content.nil? return content.to_s if content.is_a?(String) # Handle array of content blocks (e.g., text + images) if content.is_a?(Array) content.map do |block| if block.is_a?(Hash) && block[:type] == "text" block[:text].to_s else "[#{block[:type] || 'content'}]" end end.join("\n") else content.to_s end end |
#generate_hierarchical_summary(messages) ⇒ Object
Generate hierarchical summary based on compression level Level 1: Detailed summary with files, decisions, features Level 2: Concise summary with key items Level 3: Minimal summary (just project type) Level 4+: Ultra-minimal (single line)
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 |
# File 'lib/clacky/agent/message_compressor_helper.rb', line 461 def generate_hierarchical_summary() level = @compression_level # Extract key information from messages extracted = extract_key_information() summary_text = case level when 1 generate_level1_summary(extracted) when 2 generate_level2_summary(extracted) when 3 generate_level3_summary(extracted) else generate_level4_summary(extracted) end { role: "user", content: "[SYSTEM][COMPRESSION LEVEL #{level}] #{summary_text}", system_injected: true, compression_level: level } end |
#generate_level1_summary(data) ⇒ Object
Level 1: Detailed summary (for first compression)
631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 |
# File 'lib/clacky/agent/message_compressor_helper.rb', line 631 def generate_level1_summary(data) parts = [] parts << "Previous conversation summary (#{data[:user_msgs]} user requests, #{data[:assistant_msgs]} responses, #{data[:tool_msgs]} tool calls):" # Files created if data[:files_created].any? files_list = data[:files_created].map { |f| File.basename(f) }.join(", ") parts << "Created: #{files_list}" end # Files modified if data[:files_modified].any? files_list = data[:files_modified].map { |f| File.basename(f) }.join(", ") parts << "Modified: #{files_list}" end # Completed tasks if data[:completed_tasks].any? tasks_list = data[:completed_tasks].first(3).join(", ") parts << "Completed: #{tasks_list}" end # In progress if data[:in_progress] parts << "In Progress: #{data[:in_progress]}" end # Key decisions if data[:decisions].any? decisions_text = data[:decisions].map { |d| d.gsub(/\n/, " ").strip }.join("; ") parts << "Decisions: #{decisions_text}" end # Tools used if data[:tools_used].any? parts << "Tools: #{data[:tools_used].join(', ')}" end parts << "Continuing with recent conversation..." parts.join("\n") end |
#generate_level2_summary(data) ⇒ Object
Level 2: Concise summary (for second compression)
675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 |
# File 'lib/clacky/agent/message_compressor_helper.rb', line 675 def generate_level2_summary(data) parts = [] parts << "Conversation summary:" # Key files (limit to most important) all_files = (data[:files_created] + data[:files_modified]).uniq if all_files.any? key_files = all_files.first(5).map { |f| File.basename(f) }.join(", ") parts << "Files: #{key_files}" end # Key accomplishments accomplishments = [] accomplishments << "#{data[:completed_tasks].size} tasks completed" if data[:completed_tasks].any? accomplishments << "#{data[:tool_msgs]} tools executed" if data[:tool_msgs] > 0 accomplishments << "Level #{data[:completed_tasks].size + 1} progress" if data[:in_progress] parts << accomplishments.join(", ") if accomplishments.any? parts << "Recent context follows..." parts.join("\n") end |
#generate_level3_summary(data) ⇒ Object
Level 3: Minimal summary (for third compression)
700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 |
# File 'lib/clacky/agent/message_compressor_helper.rb', line 700 def generate_level3_summary(data) parts = [] parts << "Project progress:" # Just counts and key items all_files = (data[:files_created] + data[:files_modified]).uniq parts << "#{all_files.size} files modified, #{data[:completed_tasks].size} tasks done" if data[:in_progress] parts << "Currently: #{data[:in_progress]}" end parts << "See recent messages for details." parts.join("\n") end |
#generate_level4_summary(data) ⇒ Object
Level 4: Ultra-minimal summary (for fourth+ compression)
718 719 720 721 |
# File 'lib/clacky/agent/message_compressor_helper.rb', line 718 def generate_level4_summary(data) all_files = (data[:files_created] + data[:files_modified]).uniq "Progress: #{data[:completed_tasks].size} tasks, #{all_files.size} files. Recent: #{data[:tools_used].last(3).join(', ')}" end |
#get_recent_messages_with_tool_pairs(messages, count) ⇒ Array
Get recent messages while preserving tool_calls/tool_results pairs. Handles both canonical format (role: “tool”) and legacy Anthropic-native format (role: “user” with tool_result content blocks).
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 226 |
# File 'lib/clacky/agent/message_compressor_helper.rb', line 179 def (, count) return [] if .nil? || .empty? = Set.new i = .size - 1 = 0 while i >= 0 && < count msg = [i] # Never include the system message — it is always prepended separately # by rebuild_with_compression. Including it here would cause it to appear # twice in the rebuilt history, inflating token counts on every compression. if msg[:role] == "system" i -= 1 next end if .include?(i) i -= 1 next end .add(i) += 1 # assistant with tool_calls → also pull in all following tool results if msg[:role] == "assistant" && msg[:tool_calls]&.any? pull_tool_results_after(, i, ) end # tool result (canonical or legacy Anthropic) → also pull in its assistant if (msg) pull_assistant_before(, i, ) do |added| += 1 if added end end i -= 1 end = .to_a.sort.map { |idx| [idx] } # Truncate large tool results to prevent token bloat .map do |msg| truncate_tool_result(msg) end end |
#handle_compression_response(response, compression_context) ⇒ Object
Handle compression response and rebuild message list
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 168 169 170 171 |
# File 'lib/clacky/agent/message_compressor_helper.rb', line 120 def handle_compression_response(response, compression_context) # Extract compressed content from response compressed_content = response[:content] # Note: Cost tracking is already handled by call_llm, no need to track again here # Rebuild message list with compression # Note: we need to remove the compression instruction message we just added = @history.to_a[0..-2] # All except the last (compression instruction) # Archive compressed messages to a chunk MD file before discarding them # Count existing compressed_summary messages in history to determine the next chunk index. # Using @compressed_summaries.size would reset to 0 on process restart and overwrite existing # chunk files, creating circular chunk references. Counting from history is always accurate. existing_chunk_count = .count { |m| m[:compressed_summary] } chunk_index = existing_chunk_count + 1 chunk_path = save_compressed_chunk( , compression_context[:recent_messages], chunk_index: chunk_index, compression_level: compression_context[:compression_level] ) @history.replace_all(@message_compressor.rebuild_with_compression( compressed_content, original_messages: , recent_messages: compression_context[:recent_messages], chunk_path: chunk_path )) # Reset to the estimated size of the rebuilt (small) history. # The compression call_llm reported the OLD large token count, so # @previous_total_tokens would still be above COMPRESSION_THRESHOLD — # without this reset the very next think() would re-trigger compression # immediately, causing an infinite loop (especially after image uploads # where base64 data inflates token counts dramatically). @previous_total_tokens = @history.estimate_tokens # Track this compression @compressed_summaries << { level: compression_context[:compression_level], message_count: compression_context[:original_message_count], timestamp: Time.now.iso8601, strategy: :insert_then_compress, chunk_path: chunk_path } # Show compression info (use estimated tokens from rebuilt history) compression_summary = "History compressed (~#{compression_context[:original_token_count]} -> ~#{@history.estimate_tokens} tokens, " \ "level #{compression_context[:compression_level]})" @ui&.show_idle_status(phase: :end, message: compression_summary) end |
#parse_shell_result(content) ⇒ Object
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 |
# File 'lib/clacky/agent/message_compressor_helper.rb', line 614 def parse_shell_result(content) return nil unless content.is_a?(String) if content.include?("passed") || content.include?("success") "tests passed" elsif content.include?("failed") || content.include?("error") "command failed" elsif content =~ /bundle install|npm install|go mod download/ "dependencies installed" elsif content.include?("Installed") content[/Installed:\s*(.+)/, 1]&.strip else nil end end |
#parse_todo_result(content) ⇒ Object
602 603 604 605 606 607 608 609 610 611 612 |
# File 'lib/clacky/agent/message_compressor_helper.rb', line 602 def parse_todo_result(content) return nil unless content.is_a?(String) if content.include?("completed") { status: :completed, task: content[/completed[:\s]*(.+)/i, 1]&.strip || "task" } elsif content.include?("added") { status: :added, task: content[/added[:\s]*(.+)/i, 1]&.strip || "task" } else nil end end |
#parse_write_result(content) ⇒ Object
589 590 591 592 593 594 595 596 597 598 599 600 |
# File 'lib/clacky/agent/message_compressor_helper.rb', line 589 def parse_write_result(content) return nil unless content.is_a?(String) # Check for "Created: path" or "Updated: path" patterns if content.include?("Created:") { action: :created, file: content[/Created:\s*(.+)/, 1]&.strip } elsif content.include?("Updated:") || content.include?("modified") { action: :modified, file: content[/Updated:\s*(.+)/, 1]&.strip || content[/File written to:\s*(.+)/, 1]&.strip } else nil end end |
#pull_assistant_before(messages, tool_result_idx, include_set) ⇒ Object
Walk backwards from tool_result_idx to find and mark its assistant message. Also marks all sibling tool results for that assistant. Yields true if the assistant was newly added (for caller to increment count).
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 |
# File 'lib/clacky/agent/message_compressor_helper.rb', line 269 def pull_assistant_before(, tool_result_idx, include_set) result_ids = tool_result_ids([tool_result_idx]) j = tool_result_idx - 1 while j >= 0 prev = [j] if prev[:role] == "assistant" && prev[:tool_calls]&.any? call_ids = prev[:tool_calls].map { |tc| tc[:id] } if (call_ids & result_ids).any? newly_added = include_set.add?(j) yield newly_added # Also pull all sibling tool results for this assistant pull_tool_results_after(, j, include_set) break end end j -= 1 end end |
#pull_tool_results_after(messages, assistant_idx, include_set) ⇒ Object
Mark all tool results immediately following messages. Stops at the first non-tool-result message.
252 253 254 255 256 257 258 259 260 261 262 263 264 |
# File 'lib/clacky/agent/message_compressor_helper.rb', line 252 def pull_tool_results_after(, assistant_idx, include_set) call_ids = [assistant_idx][:tool_calls].map { |tc| tc[:id] } j = assistant_idx + 1 while j < .size nxt = [j] if tool_result_for?(nxt, call_ids) include_set.add(j) elsif !(nxt) break end j += 1 end end |
#save_compressed_chunk(original_messages, recent_messages, chunk_index:, compression_level:) ⇒ String?
Save the messages being compressed to a chunk MD file for future recall File path: ~/.clacky/sessions/datetime-short_id-chunk-n.md
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 336 |
# File 'lib/clacky/agent/message_compressor_helper.rb', line 307 def save_compressed_chunk(, , chunk_index:, compression_level:) return nil unless @session_id && @created_at # Messages being compressed = original minus system message minus recent messages # Also exclude system-injected scaffolding (session context, memory prompts, etc.) # — these are internal CLI metadata and must not appear in chunk MD or WebUI history. recent_set = .to_a = .reject do |m| m[:role] == "system" || m[:system_injected] || recent_set.include?(m) end return nil if .empty? sessions_dir = Clacky::SessionManager::SESSIONS_DIR datetime = Time.parse(@created_at).strftime("%Y-%m-%d-%H-%M-%S") short_id = @session_id[0..7] base_name = "#{datetime}-#{short_id}" chunk_filename = "#{base_name}-chunk-#{chunk_index}.md" chunk_path = File.join(sessions_dir, chunk_filename) md_content = build_chunk_md(, chunk_index: chunk_index, compression_level: compression_level) File.write(chunk_path, md_content) FileUtils.chmod(0o600, chunk_path) chunk_path rescue => e @ui&.log("Failed to save chunk MD: #{e.}", level: :warn) nil end |
#tool_result_for?(msg, call_ids) ⇒ Boolean
Returns true if msg is a tool result that matches any of the given call IDs.
246 247 248 |
# File 'lib/clacky/agent/message_compressor_helper.rb', line 246 def tool_result_for?(msg, call_ids) (msg) && (tool_result_ids(msg) & call_ids).any? end |
#tool_result_ids(msg) ⇒ Object
Returns the tool_call IDs referenced in a tool result message.
237 238 239 240 241 242 243 |
# File 'lib/clacky/agent/message_compressor_helper.rb', line 237 def tool_result_ids(msg) if MessageFormat::OpenAI.(msg) MessageFormat::OpenAI.tool_call_ids(msg) else MessageFormat::Anthropic.tool_use_ids(msg) end end |
#tool_result_message?(msg) ⇒ Boolean
Returns true if msg is a tool result, regardless of storage format. Canonical: role:“tool” | Legacy Anthropic-native: role:“user” + tool_result blocks
231 232 233 234 |
# File 'lib/clacky/agent/message_compressor_helper.rb', line 231 def (msg) MessageFormat::OpenAI.(msg) || MessageFormat::Anthropic.(msg) end |
#trigger_idle_compression ⇒ Object
Trigger compression during idle time (user-friendly, interruptible) Returns true if compression was performed, false otherwise
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
# File 'lib/clacky/agent/message_compressor_helper.rb', line 17 def trigger_idle_compression # Check if we should compress (force mode) compression_context = (force: true) @ui&.show_idle_status(phase: :start, message: "Idle detected. Compressing conversation to optimize costs...") if compression_context.nil? @ui&.show_idle_status(phase: :end, message: "Idle skipped.") Clacky::Logger.info( "Idle compression skipped", enable_compression: @config.enable_compression, previous_total_tokens: @previous_total_tokens, history_size: @history.size, idle_threshold: IDLE_COMPRESSION_THRESHOLD, max_recent_messages: MAX_RECENT_MESSAGES ) return false end # Insert compression message = compression_context[:compression_message] @history.append() begin # Execute compression using shared LLM call logic response = call_llm handle_compression_response(response, compression_context) true rescue Clacky::AgentInterrupted => e @ui&.log("Idle compression canceled: #{e.}", level: :info) @history.rollback_before() false rescue => e @ui&.log("Idle compression failed: #{e.}", level: :error) @history.rollback_before() false end end |
#truncate_content(text, max_length: 500) ⇒ Object
Truncate long content with a note
437 438 439 440 |
# File 'lib/clacky/agent/message_compressor_helper.rb', line 437 def truncate_content(text, max_length: 500) return text if text.length <= max_length "#{text[0...max_length]}\n... [truncated, #{text.length} chars total]" end |
#truncate_tool_result(msg) ⇒ Object
Truncate oversized tool result content to avoid token bloat.
291 292 293 294 295 296 297 298 |
# File 'lib/clacky/agent/message_compressor_helper.rb', line 291 def truncate_tool_result(msg) if MessageFormat::OpenAI.(msg) && msg[:content].is_a?(String) && msg[:content].length > 2000 msg.merge(content: msg[:content][0..2000] + "...\n[Content truncated - exceeded 2000 characters]") else msg end end |