1use eyre::Result;
2use glob::glob;
3use regex::Regex;
4use rig_core::completion::ToolDefinition;
5use serde_json::{Value, json};
6use std::collections::HashMap;
7use std::path::{Path, PathBuf};
8use std::pin::Pin;
9use std::sync::Arc;
10use tokio::fs;
11use tracing::debug;
12
13pub fn floor_char_boundary(s: &str, pos: usize) -> usize {
16 let pos = pos.min(s.len());
17 let bytes = s.as_bytes();
20 for i in (0..=pos).rev() {
21 if i == 0 || (bytes[i] & 0xC0) != 0x80 {
22 return i;
23 }
24 }
25 0
26}
27
28const ALLOWED_GIT_SUBCOMMANDS: &[&str] = &[
32 "diff",
33 "log",
34 "show",
35 "blame",
36 "status",
37 "rev-parse",
38 "shortlog",
39 "ls-files",
40 "for-each-ref",
41 "show-ref",
42];
43
44fn long_flag_matches(token: &str, name: &str) -> bool {
48 long_flag_stem(token).is_some_and(|stem| name.starts_with(stem))
49}
50
51fn long_flag_stem(token: &str) -> Option<&str> {
52 token
53 .strip_prefix("--")
54 .map(|long| long.split('=').next().unwrap_or(long))
55 .filter(|stem| !stem.is_empty())
56}
57
58fn blocked_fs_reading_flag_matches(token: &str, name: &str) -> bool {
59 if name == "ignore-revs-file" && long_flag_stem(token) == Some("ignore-rev") {
60 return false;
61 }
62 long_flag_matches(token, name)
63}
64
65fn ensure_readonly_git(subcommand: &str, rest: &[&str]) -> std::result::Result<(), String> {
72 for token in rest {
77 let value = match token.starts_with('-') {
78 true => token.split_once('=').map(|(_, v)| v).unwrap_or(""),
79 false => token,
80 };
81 if looks_like_external_path(value) {
82 return Err(format!(
83 "Error: git argument '{token}' references a path outside the repository"
84 ));
85 }
86 }
87 let fs_reading_flags: &[&str] = match subcommand {
91 "diff" => &["no-index"],
92 "blame" => &["contents", "ignore-revs-file"],
93 _ => &[],
94 };
95 for flag in fs_reading_flags {
96 if rest
97 .iter()
98 .any(|token| blocked_fs_reading_flag_matches(token, flag))
99 {
100 return Err(format!(
101 "Error: git --{flag} reads files outside the repository and is not allowed"
102 ));
103 }
104 }
105 if matches!(subcommand, "diff" | "log" | "show") {
109 for token in rest {
110 if long_flag_matches(token, "output")
111 || *token == "-o"
112 || (token.starts_with("-o") && !token.starts_with("--") && token.len() > 2)
113 {
114 return Err(
115 "Error: writing git output to a file (--output/-o) is not allowed".into(),
116 );
117 }
118 }
119 }
120 Ok(())
121}
122
123fn looks_like_external_path(value: &str) -> bool {
124 if value.is_empty() {
125 return false;
126 }
127 Path::new(value).is_absolute()
128 || value.starts_with('\\')
129 || has_windows_drive_prefix(value)
130 || value.split(['/', '\\']).any(|component| component == "..")
131}
132
133fn has_windows_drive_prefix(value: &str) -> bool {
134 let bytes = value.as_bytes();
135 bytes.len() >= 3
136 && bytes[0].is_ascii_alphabetic()
137 && bytes[1] == b':'
138 && matches!(bytes.get(2).copied(), Some(b'/' | b'\\'))
139}
140
141pub trait Tool: Send + Sync {
142 fn name(&self) -> String;
143 fn definition(&self) -> ToolDefinition;
144 fn call(
145 &self,
146 args: Value,
147 work_dir: PathBuf,
148 ) -> Pin<Box<dyn std::future::Future<Output = Result<String>> + Send>>;
149}
150
151pub fn all_tools() -> HashMap<String, Arc<dyn Tool>> {
152 let tools: Vec<Arc<dyn Tool>> = vec![
153 Arc::new(ReadFileTool),
154 Arc::new(GlobTool),
155 Arc::new(GrepTool),
156 Arc::new(GitTool),
157 ];
158 tools.into_iter().map(|tool| (tool.name(), tool)).collect()
159}
160
161pub fn reflect_tools() -> HashMap<String, Arc<dyn Tool>> {
162 let tools: Vec<Arc<dyn Tool>> = vec![
163 Arc::new(ReadFileTool),
164 Arc::new(GlobTool),
165 Arc::new(GrepTool),
166 ];
167 tools.into_iter().map(|tool| (tool.name(), tool)).collect()
168}
169
170pub fn tool_definitions(tools: &HashMap<String, Arc<dyn Tool>>) -> Vec<ToolDefinition> {
171 tools.values().map(|tool| tool.definition()).collect()
172}
173
174pub struct ReadFileTool;
175
176impl Tool for ReadFileTool {
177 fn name(&self) -> String {
178 "read_file".to_string()
179 }
180
181 fn definition(&self) -> ToolDefinition {
182 ToolDefinition {
183 name: "read_file".to_string(),
184 description:
185 "Read a text file inside the workspace and return numbered lines. Use this after glob or grep to inspect specific files; prefer start_line/end_line for focused reads."
186 .to_string(),
187 parameters: json!({
188 "type": "object",
189 "properties": {
190 "path": {
191 "type": "string",
192 "description": "Workspace-relative file path to read."
193 },
194 "start_line": {
195 "type": "integer",
196 "minimum": 1,
197 "description": "First line to include. Omit to start at line 1."
198 },
199 "end_line": {
200 "type": "integer",
201 "minimum": 1,
202 "description": "Last line to include. Omit to read to the end of the file."
203 }
204 },
205 "required": ["path"],
206 "additionalProperties": false
207 }),
208 }
209 }
210
211 fn call(
212 &self,
213 args: Value,
214 work_dir: PathBuf,
215 ) -> Pin<Box<dyn std::future::Future<Output = Result<String>> + Send>> {
216 Box::pin(async move {
217 let path = args
218 .get("path")
219 .and_then(|value| value.as_str())
220 .ok_or_else(|| eyre::eyre!("missing path"))?;
221 let start_line = args
222 .get("start_line")
223 .and_then(|value| value.as_u64())
224 .unwrap_or(1) as usize;
225 let end_line = args
226 .get("end_line")
227 .and_then(|value| value.as_u64())
228 .map(|value| value as usize);
229 let full_path = work_dir.join(path);
230 let full_path = full_path.canonicalize().map_err(|e| {
231 eyre::eyre!(
232 "cannot resolve path {path:?}: {e}. Only files within {} are accessible.",
233 work_dir.display()
234 )
235 })?;
236 if !full_path.starts_with(&work_dir) {
237 eyre::bail!(
238 "access denied: {path:?} is outside the allowed workspace ({}). Only project files are accessible.",
239 work_dir.display()
240 );
241 }
242 let content = match fs::read_to_string(&full_path).await {
243 Ok(content) => content,
244 Err(err) if err.kind() == std::io::ErrorKind::InvalidData => {
245 eyre::bail!("file is not valid UTF-8; read_file only supports text files")
246 }
247 Err(err) => return Err(err.into()),
248 };
249 let lines = content.lines().collect::<Vec<_>>();
250 let total = lines.len();
251 let start = start_line.max(1).min(total.max(1));
252 let end = end_line.unwrap_or(total).max(start).min(total);
253 let relative = full_path
254 .strip_prefix(&work_dir)
255 .unwrap_or(&full_path)
256 .display()
257 .to_string();
258 let mut output = format!("File: {relative}\nLines: {start}-{end} of {total}\n\n");
259 for (idx, line) in lines.iter().enumerate() {
260 let line_num = idx + 1;
261 if line_num < start || line_num > end {
262 continue;
263 }
264 output.push_str(&format!("{line_num:>4} {line}\n"));
265 }
266 Ok(output)
267 })
268 }
269}
270
271pub struct GlobTool;
272
273impl Tool for GlobTool {
274 fn name(&self) -> String {
275 "glob".to_string()
276 }
277
278 fn definition(&self) -> ToolDefinition {
279 ToolDefinition {
280 name: "glob".to_string(),
281 description:
282 "Find workspace-relative file paths by glob pattern. Use this when you know the file name or extension pattern but not the exact path; returns at most 200 matches."
283 .to_string(),
284 parameters: json!({
285 "type": "object",
286 "properties": {
287 "pattern": {
288 "type": "string",
289 "description": "Workspace-relative glob such as 'src/**/*.rs' or '**/*.toml'."
290 }
291 },
292 "required": ["pattern"],
293 "additionalProperties": false
294 }),
295 }
296 }
297
298 fn call(
299 &self,
300 args: Value,
301 work_dir: PathBuf,
302 ) -> Pin<Box<dyn std::future::Future<Output = Result<String>> + Send>> {
303 Box::pin(async move {
304 let pattern = args
305 .get("pattern")
306 .and_then(|value| value.as_str())
307 .ok_or_else(|| eyre::eyre!("missing pattern"))?;
308 let pattern_path = Path::new(pattern);
309 if pattern_path.is_absolute()
310 || pattern_path
311 .components()
312 .any(|c| c == std::path::Component::ParentDir)
313 {
314 eyre::bail!(
315 "access denied: glob pattern {pattern:?} must be relative to the workspace ({}). Absolute paths and parent-directory traversal are not allowed.",
316 work_dir.display()
317 );
318 }
319 let mut results = Vec::new();
320 let full_pattern = work_dir.join(pattern);
321 let full_pattern = full_pattern.to_string_lossy();
322 for entry in glob(&full_pattern)? {
323 if let Ok(path) = entry {
324 if let Ok(relative) = path.strip_prefix(&work_dir) {
325 results.push(relative.display().to_string());
326 }
327 }
328 if results.len() >= 200 {
329 break;
330 }
331 }
332 if results.is_empty() {
333 return Ok(format!("No files matched pattern: {pattern}"));
334 }
335 Ok(results.join("\n"))
336 })
337 }
338}
339
340pub struct GrepTool;
341
342impl Tool for GrepTool {
343 fn name(&self) -> String {
344 "grep".to_string()
345 }
346
347 fn definition(&self) -> ToolDefinition {
348 ToolDefinition {
349 name: "grep".to_string(),
350 description: "Search text files for a regex and return path:line:content matches. Use this to locate relevant code before calling read_file; optionally limit by path or file_glob, and expect at most 100 matches."
351 .to_string(),
352 parameters: json!({
353 "type": "object",
354 "properties": {
355 "pattern": {
356 "type": "string",
357 "description": "Regular expression to search for in file contents."
358 },
359 "path": {
360 "type": "string",
361 "description": "Optional workspace-relative file or directory to search within."
362 },
363 "file_glob": {
364 "type": "string",
365 "description": "Optional filename filter such as '*.rs'; matched against file names, not full paths."
366 }
367 },
368 "required": ["pattern"],
369 "additionalProperties": false
370 }),
371 }
372 }
373
374 fn call(
375 &self,
376 args: Value,
377 work_dir: PathBuf,
378 ) -> Pin<Box<dyn std::future::Future<Output = Result<String>> + Send>> {
379 Box::pin(async move {
380 let pattern = args
381 .get("pattern")
382 .and_then(|value| value.as_str())
383 .ok_or_else(|| eyre::eyre!("missing pattern"))?;
384 let base_path = args
385 .get("path")
386 .and_then(|value| value.as_str())
387 .map(|value| {
388 let p = work_dir.join(value);
389 p.canonicalize()
391 .map_err(|e| eyre::eyre!("cannot resolve path {value:?}: {e}. Only files within {} are accessible.", work_dir.display()))
392 })
393 .transpose()?
394 .unwrap_or_else(|| work_dir.clone());
395 if !base_path.starts_with(&work_dir) {
396 let path_arg = args.get("path").and_then(|v| v.as_str()).unwrap_or("?");
397 eyre::bail!(
398 "access denied: {path_arg:?} is outside the allowed workspace ({}). Only project files are accessible.",
399 work_dir.display()
400 );
401 }
402 let file_glob = args
403 .get("file_glob")
404 .and_then(|value| value.as_str())
405 .map(glob_to_regex)
406 .transpose()?;
407 let regex =
408 Regex::new(pattern).map_err(|e| eyre::eyre!("invalid regex {pattern:?}: {e}"))?;
409 let mut results = Vec::new();
410 let mut skipped_files = 0usize;
411 if base_path.is_file() {
412 if let Err(e) = search_file(&base_path, ®ex, &work_dir, &mut results).await {
413 debug!("skipping file {}: {e}", base_path.display());
414 skipped_files += 1;
415 }
416 } else {
417 let mut stack = vec![base_path];
418 while let Some(path) = stack.pop() {
419 let entries = match fs::read_dir(&path).await {
420 Ok(entries) => entries,
421 Err(e) => {
422 debug!("skipping unreadable dir {}: {e}", path.display());
423 continue;
424 }
425 };
426 let mut entries = entries;
427 while let Ok(Some(entry)) = entries.next_entry().await {
428 let entry_path = entry.path();
429 let file_type = match entry.file_type().await {
430 Ok(file_type) => file_type,
431 Err(e) => {
432 debug!("skipping {}: {e}", entry_path.display());
433 continue;
434 }
435 };
436 let name = entry.file_name();
437 let name = name.to_string_lossy();
438 if file_type.is_dir() {
439 if name.starts_with('.') || name == "target" || name == "node_modules" {
440 continue;
441 }
442 stack.push(entry_path);
443 } else if file_type.is_file() {
444 if let Some(filter) = &file_glob {
445 if !filter.is_match(&name) {
446 continue;
447 }
448 }
449 match search_file(&entry_path, ®ex, &work_dir, &mut results).await {
450 Ok(_) => {}
451 Err(e) => {
452 debug!("skipping file {}: {e}", entry_path.display());
453 skipped_files += 1;
454 }
455 }
456 if results.len() >= 100 {
457 break;
458 }
459 }
460 if results.len() >= 100 {
461 break;
462 }
463 }
464 if results.len() >= 100 {
465 break;
466 }
467 }
468 }
469 if results.is_empty() {
470 let mut output = format!("No matches for regex: {pattern}");
471 if skipped_files > 0 {
472 output.push_str(&format!("\nSkipped unreadable files: {skipped_files}"));
473 }
474 return Ok(output);
475 }
476 let mut output = format!("Matches: {}\n", results.len());
477 if skipped_files > 0 {
478 output.push_str(&format!("Skipped unreadable files: {skipped_files}\n"));
479 }
480 output.push('\n');
481 output.push_str(&results.join("\n"));
482 Ok(output)
483 })
484 }
485}
486
487async fn search_file(
488 path: &PathBuf,
489 regex: &Regex,
490 work_dir: &Path,
491 results: &mut Vec<String>,
492) -> Result<()> {
493 use tokio::io::AsyncReadExt;
494
495 let mut file = fs::File::open(path).await?;
497 let mut buffer = [0u8; 8192];
498 let bytes_read = file.read(&mut buffer).await?;
499
500 if buffer[..bytes_read].contains(&0) {
502 return Ok(()); }
504
505 let mut remaining = Vec::new();
507 file.read_to_end(&mut remaining).await?;
508
509 let mut full_content = Vec::with_capacity(bytes_read + remaining.len());
511 full_content.extend_from_slice(&buffer[..bytes_read]);
512 full_content.extend_from_slice(&remaining);
513
514 let content = String::from_utf8_lossy(&full_content);
516 let relative = path.strip_prefix(work_dir).unwrap_or(path);
517 for (idx, line) in content.lines().enumerate() {
518 if regex.is_match(line) {
519 results.push(format!("{}:{}:{}", relative.display(), idx + 1, line));
520 if results.len() >= 100 {
521 break;
522 }
523 }
524 }
525 Ok(())
526}
527
528fn glob_to_regex(pattern: &str) -> Result<Regex> {
529 let mut escaped = String::new();
530 for ch in pattern.chars() {
531 match ch {
532 '.' => escaped.push_str("\\."),
533 '*' => escaped.push_str(".*"),
534 '?' => escaped.push('.'),
535 other => escaped.push(other),
536 }
537 }
538 Regex::new(&format!("^{}$", escaped))
539 .map_err(|e| eyre::eyre!("invalid file_glob {pattern:?}: {e}"))
540}
541
542pub async fn is_binary_file(path: &Path) -> std::io::Result<bool> {
545 use tokio::io::AsyncReadExt;
546 let mut file = fs::File::open(path).await?;
547 let mut buffer = [0u8; 8192];
548 let bytes_read = file.read(&mut buffer).await?;
549 Ok(buffer[..bytes_read].contains(&0)) }
551
552pub struct GitTool;
553
554impl Tool for GitTool {
555 fn name(&self) -> String {
556 "git".to_string()
557 }
558
559 fn definition(&self) -> ToolDefinition {
560 ToolDefinition {
561 name: "git".to_string(),
562 description: "Run an allowlisted read-only git command for review context: diff, log, show, blame, status, rev-parse, shortlog, ls-files, for-each-ref, show-ref. To list or query branches/tags use for-each-ref (e.g. `for-each-ref --contains <sha> refs/heads/`), not branch/tag. Use this for repository history or patch context, not for general file search."
563 .to_string(),
564 parameters: json!({
565 "type": "object",
566 "properties": {
567 "command": {
568 "type": "string",
569 "description": "Read-only git command to run, for example 'diff --stat HEAD~1' or 'log --oneline -n 20'."
570 }
571 },
572 "required": ["command"],
573 "additionalProperties": false
574 }),
575 }
576 }
577
578 fn call(
579 &self,
580 args: Value,
581 work_dir: PathBuf,
582 ) -> Pin<Box<dyn std::future::Future<Output = Result<String>> + Send>> {
583 Box::pin(async move {
584 let command = args
585 .get("command")
586 .and_then(|value| value.as_str())
587 .ok_or_else(|| eyre::eyre!("missing command"))?;
588 let tokens = command.split_whitespace().collect::<Vec<_>>();
589 let Some((subcommand, rest)) = tokens.split_first() else {
590 return Ok("Error: empty git command".to_string());
591 };
592 if !ALLOWED_GIT_SUBCOMMANDS.contains(subcommand) {
593 return Ok(format!("Error: git subcommand '{subcommand}' not allowed"));
594 }
595 if let Err(msg) = ensure_readonly_git(subcommand, rest) {
596 return Ok(msg);
597 }
598 let output = tokio::process::Command::new("git")
602 .args(tokens)
603 .env("GIT_OPTIONAL_LOCKS", "0")
604 .current_dir(&work_dir)
605 .output()
606 .await?;
607 let mut stdout = String::from_utf8_lossy(&output.stdout).to_string();
608 if stdout.len() > 50_000 {
609 let original_len = stdout.len();
610 let boundary = floor_char_boundary(&stdout, 50_000);
611 stdout.truncate(boundary);
612 stdout.push_str(&format!(
613 "\n... truncated after 50,000 chars; {} chars omitted",
614 original_len.saturating_sub(boundary)
615 ));
616 }
617 if !output.status.success() {
618 let stderr = String::from_utf8_lossy(&output.stderr);
619 return Ok(format!("Error: {stderr}"));
620 }
621 Ok(stdout)
622 })
623 }
624}
625
626#[cfg(test)]
627mod tests {
628 use super::{ALLOWED_GIT_SUBCOMMANDS, ReadFileTool, Tool, ensure_readonly_git};
629 use serde_json::json;
630
631 fn check(cmd: &str) -> Result<(), String> {
633 let tokens: Vec<&str> = cmd.split_whitespace().collect();
634 let (sub, rest) = tokens.split_first().expect("non-empty command");
635 if !ALLOWED_GIT_SUBCOMMANDS.contains(sub) {
636 return Err(format!("subcommand '{sub}' not allowed"));
637 }
638 ensure_readonly_git(sub, rest)
639 }
640
641 #[test]
642 fn rejects_output_file_write() {
643 assert!(check("diff HEAD~1 --output=/tmp/evil").is_err());
645 assert!(check("diff --output ../escape.txt HEAD~1").is_err());
646 assert!(check("log --oneline -o /tmp/x").is_err());
647 assert!(check("show -o/tmp/glued HEAD").is_err());
648 assert!(check("diff --out=/tmp/abbrev HEAD~1").is_err()); }
650
651 #[test]
652 fn allows_plain_read_commands() {
653 assert!(check("diff HEAD~1").is_ok());
654 assert!(check("log --oneline -n 5").is_ok());
655 assert!(check("show HEAD").is_ok());
656 assert!(check("status --porcelain").is_ok());
657 assert!(check("log --oneline").is_ok());
659 assert!(check("ls-files -o --exclude-standard").is_ok());
661 assert!(check("ls-files --others").is_ok());
662 assert!(check("diff --stat HEAD~1 -- src/foo.rs").is_ok());
664 assert!(check("log origin/main..HEAD").is_ok());
665 assert!(check("blame -- src/foo.rs").is_ok());
666 assert!(check("blame --ignore-rev HEAD -- src/foo.rs").is_ok());
667 assert!(check("blame --ignore-rev=HEAD -- src/foo.rs").is_ok());
668 assert!(check("show HEAD:src/foo.rs").is_ok());
669 assert!(check("show v:src/foo.rs").is_ok());
670 assert!(check("diff HEAD -- ./src").is_ok());
671 assert!(check(r"diff HEAD -- src\foo.rs").is_ok());
672 }
673
674 #[test]
675 fn rejects_arbitrary_file_read() {
676 assert!(check("diff --no-index /etc/passwd /dev/null").is_err());
679 assert!(check("diff --no-i /etc/passwd /dev/null").is_err()); assert!(check("diff --no-index a b").is_err()); assert!(check("blame --contents /etc/passwd -- a.txt").is_err());
682 assert!(check("blame --contents=/etc/passwd -- a.txt").is_err());
683 assert!(check("blame --contents secret.txt -- a.txt").is_err());
684 assert!(check("diff /etc/passwd").is_err());
686 assert!(check("log -- ../../../etc/passwd").is_err());
687 assert!(check("show ../outside").is_err());
688 assert!(check("diff HEAD -- a/../../../etc/passwd").is_err());
689 }
690
691 #[test]
692 fn rejects_windows_style_path_escapes() {
693 assert!(check(r"diff C:\Users\victim\secret").is_err());
694 assert!(check(r"diff C:/Users/victim\secret").is_err());
695 assert!(check(r"diff \\server\share\secret").is_err());
696 assert!(check(r"log -- ..\secret").is_err());
697 assert!(check(r"show a\..\secret").is_err());
698 }
699
700 #[test]
701 fn rejects_blame_revision_file_reads() {
702 assert!(check("blame --ignore-revs-file README.md -- src/tools.rs").is_err());
703 assert!(check("blame --ignore-revs-file=README.md -- src/tools.rs").is_err());
704 assert!(check("blame --ignore-revs README.md -- src/tools.rs").is_err());
705 assert!(check("blame --ignore-revs-f=README.md -- src/tools.rs").is_err());
706 }
707
708 #[tokio::test]
709 async fn read_file_invalid_utf8_reports_text_only_feedback() {
710 let dir = tempfile::tempdir().unwrap();
711 std::fs::write(dir.path().join("bin.dat"), [0xff, 0xfe]).unwrap();
712 let work_dir = dir.path().canonicalize().unwrap();
713
714 let err = ReadFileTool
715 .call(json!({ "path": "bin.dat" }), work_dir)
716 .await
717 .unwrap_err()
718 .to_string();
719
720 assert_eq!(
721 err,
722 "file is not valid UTF-8; read_file only supports text files"
723 );
724 }
725
726 #[test]
727 fn rejects_branch_and_tag_porcelain() {
728 assert!(check("branch -D some-branch").is_err());
731 assert!(check("branch new-branch").is_err());
732 assert!(check("branch --set-upstream-to=origin/main").is_err());
733 assert!(check("branch -- newbranch").is_err());
734 assert!(check("tag v9.9.9").is_err());
735 assert!(check("tag -d v1").is_err());
736 assert!(check("branch --list").is_err());
738 }
739
740 #[test]
741 fn allows_readonly_ref_plumbing() {
742 assert!(check("for-each-ref refs/heads/").is_ok());
744 assert!(check("for-each-ref --contains HEAD refs/heads/").is_ok());
745 assert!(check("for-each-ref --format=%(refname) --sort=-creatordate").is_ok());
746 assert!(check("show-ref --tags").is_ok());
747 assert!(check("show-ref --heads").is_ok());
748 }
751}