Commit ee75cce

mo khan <mo@mokhan.ca>
2025-08-28 17:42:34
refactor: improve search tool
1 parent 91f7747
Changed files (3)
lib
lib/elelem/states/working.rb
@@ -8,13 +8,29 @@ module Elelem
           state = Waiting.new(agent)
 
           loop do
+            done = false
             agent.api.chat(agent.conversation.history) do |message|
+              if message["done"]
+                done = true
+                next
+              end
+
               agent.logger.debug("#{state.display_name}: #{message}")
               state = state.run(message)
             end
 
             break if state.nil?
             break if agent.conversation.history.last[:role] == :assistant && agent.conversation.history.last[:content]&.strip&.end_with?("I am finished with the task.")
+
+            # For simple responses, check if we should return to idle
+            if done && agent.conversation.history.last[:role] == :assistant && 
+               !agent.conversation.history.last[:content]&.strip&.end_with?("I am finished with the task.")
+              # Check if this looks like a simple response (no pending tools/reasoning)
+              last_message = agent.conversation.history.last[:content]&.strip
+              if last_message && !last_message.empty?
+                break
+              end
+            end
           end
 
           agent.transition_to(States::Idle.new)
lib/elelem/toolbox/search.rb
@@ -23,9 +23,22 @@ module Elelem
 
       def call(args)
         path = args["path"] || "."
-        `grep -rnw '#{args["pattern"]}' #{path}`
-      rescue => e
-        e.message
+        pattern = args["pattern"]
+
+        # Build search command - use git grep if in git repo, otherwise regular grep
+        if ::File.directory?(".git") || `git rev-parse --git-dir 2>/dev/null`.strip != ""
+          # Limit results: -m 3 = max 3 matches per file, head -20 = max 20 total lines
+          command = "git grep -n -m 3 '#{pattern}'"
+          command += " -- #{path}" unless path == "."
+          command += " | head -20"
+        else
+          # For regular grep, also limit results
+          command = "grep -rnw '#{pattern}' #{path} | head -20"
+        end
+
+        # Delegate to bash tool for consistent logging and streaming
+        bash_tool = Elelem::Toolbox::Bash.new(@configuration)
+        bash_tool.call({ "command" => command })
       end
     end
   end
lib/elelem/api.rb
@@ -23,7 +23,12 @@ module Elelem
             buffer += chunk
 
             while (message = extract_sse_message(buffer))
-              next if message.empty? || message == "[DONE]"
+              next if message.empty?
+
+              if message == "[DONE]"
+                block.call({ "done" => true })
+                break
+              end
 
               configuration.logger.debug(message)
               json = JSON.parse(message)