Class: Kreator::Tools::Grep

Inherits:
Object
  • Object
show all
Defined in:
lib/kreator/tools/grep.rb

Constant Summary collapse

DEFAULT_MAX_RESULTS =
100
DEFAULT_MAX_BYTES =
20_000
BINARY_SAMPLE_BYTES =
4096

Instance Method Summary collapse

Instance Method Details

#call(args:, context:, signal:) ⇒ Object



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
# File 'lib/kreator/tools/grep.rb', line 35

def call(args:, context:, signal:)
  root = allowed_path(args.fetch("path", "."), context)
  pattern = compile_pattern(args.fetch("pattern"), args.fetch("case_sensitive", true))
  include_hidden = args.fetch("include_hidden", false)
  glob = args["glob"]
  max_results = args.fetch("max_results", DEFAULT_MAX_RESULTS)
  max_bytes = args.fetch("max_bytes", DEFAULT_MAX_BYTES)
  matches = []
  scanned = 0

  candidate_files(root, include_hidden, glob).each do |path|
    context.ensure_not_cancelled!(signal)
    next if binary_file?(path)

    scanned += 1
    grep_file(path, root, pattern, matches, max_results + 1)
    break if matches.length > max_results
  end

  visible_matches = matches.first(max_results)
  result_truncated = matches.length > max_results
  content, byte_truncated = truncate_content(format_matches(visible_matches), max_bytes)
  ToolResult.new(
    tool_call_id: "",
    name: name,
    content: content.empty? ? "(no matches)" : content,
    metadata: {
      "path" => root,
      "scanned_files" => scanned,
      "matches" => visible_matches.length,
      "result_truncated" => result_truncated,
      "byte_truncated" => byte_truncated
    }
  )
end

#descriptionObject



14
15
16
# File 'lib/kreator/tools/grep.rb', line 14

def description
  "Search UTF-8 text files for a Ruby regular expression with path allowlist checks and truncation."
end

#nameObject



10
11
12
# File 'lib/kreator/tools/grep.rb', line 10

def name
  "grep"
end

#schemaObject



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/kreator/tools/grep.rb', line 18

def schema
  {
    "type" => "object",
    "additionalProperties" => false,
    "required" => ["pattern"],
    "properties" => {
      "pattern" => { "type" => "string", "minLength" => 1 },
      "path" => { "type" => "string", "minLength" => 1 },
      "case_sensitive" => { "type" => "boolean" },
      "include_hidden" => { "type" => "boolean" },
      "glob" => { "type" => "string", "minLength" => 1 },
      "max_results" => { "type" => "integer", "minimum" => 1 },
      "max_bytes" => { "type" => "integer", "minimum" => 1 }
    }
  }
end