ireri-code 2.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
agent/tools/files.py ADDED
@@ -0,0 +1,322 @@
1
+ """File system tools for ireri."""
2
+
3
+ import os
4
+ from pathlib import Path
5
+ from typing import Any, Dict, List, Optional
6
+ from pydantic import BaseModel, Field
7
+
8
+ from . import Tool, ToolArgument, ToolResult, register_tool, get_registry
9
+ from agent.config import get_config
10
+
11
+ import logging
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ def _resolve_path(path: str) -> Path:
17
+ """Resolve a path relative to workspace root, preventing traversal."""
18
+ config = get_config()
19
+ workspace = config.workspace_root
20
+
21
+ # Normalize path: handle Unix-style Windows paths like /c/..., /d/...
22
+ # Also handle special paths like /workspace
23
+ normalized_path = path
24
+ if path == "/workspace" or path == "/workspace/":
25
+ normalized_path = "."
26
+ elif path.startswith('/') and len(path) >= 3 and path[2] == '/':
27
+ # Looks like /c/..., /d/... - Unix-style Windows path
28
+ # Strip the leading /c/ and treat as relative
29
+ normalized_path = path[3:]
30
+
31
+ # If the normalized path equals the workspace root path, use "."
32
+ workspace_str = str(workspace).replace('\\', '/')
33
+ if normalized_path == workspace_str or normalized_path == workspace_str.rstrip('/'):
34
+ normalized_path = "."
35
+
36
+ # Convert to Path and resolve
37
+ target = (workspace / normalized_path).resolve()
38
+
39
+ # Ensure the target is within workspace
40
+ try:
41
+ target.relative_to(workspace)
42
+ except ValueError:
43
+ raise ValueError(f"Path '{path}' attempts to escape workspace")
44
+
45
+ return target
46
+
47
+
48
+ class ListFilesArgs(ToolArgument):
49
+ """Arguments for listing files."""
50
+ path: str = Field(default=".", description="Directory path to list")
51
+ recursive: bool = Field(default=False, description="List recursively")
52
+
53
+
54
+ class ListFilesTool(Tool):
55
+ """List files in a directory."""
56
+
57
+ name = "list_files"
58
+ description = "List files and directories in a given path"
59
+ args_schema = ListFilesArgs
60
+
61
+ async def execute(self, args: ListFilesArgs) -> ToolResult:
62
+ try:
63
+ target = _resolve_path(args.path)
64
+
65
+ if not target.exists():
66
+ return ToolResult(success=False, error=f"Path does not exist: {args.path}")
67
+
68
+ if not target.is_dir():
69
+ return ToolResult(success=False, error=f"Path is not a directory: {args.path}")
70
+
71
+ files = []
72
+ if args.recursive:
73
+ for item in target.rglob("*"):
74
+ rel = item.relative_to(get_config().workspace_root)
75
+ files.append({
76
+ "path": str(rel),
77
+ "type": "directory" if item.is_dir() else "file",
78
+ "size": item.stat().st_size if item.is_file() else None,
79
+ })
80
+ else:
81
+ for item in target.iterdir():
82
+ rel = item.relative_to(get_config().workspace_root)
83
+ files.append({
84
+ "path": str(rel),
85
+ "type": "directory" if item.is_dir() else "file",
86
+ "size": item.stat().st_size if item.is_file() else None,
87
+ })
88
+
89
+ return ToolResult(
90
+ success=True,
91
+ output={"files": files, "path": args.path},
92
+ metadata={"count": len(files)}
93
+ )
94
+ except Exception as e:
95
+ logger.error(f"list_files error: {e}")
96
+ return ToolResult(success=False, error=str(e))
97
+
98
+
99
+ class ReadFileArgs(ToolArgument):
100
+ """Arguments for reading a file."""
101
+ path: str = Field(description="File path to read")
102
+ offset: Optional[int] = Field(default=None, description="Line offset to start reading from")
103
+ limit: Optional[int] = Field(default=None, description="Maximum number of lines to read")
104
+
105
+
106
+ class ReadFileTool(Tool):
107
+ """Read a file's contents."""
108
+
109
+ name = "read_file"
110
+ description = "Read the contents of a file"
111
+ args_schema = ReadFileArgs
112
+
113
+ async def execute(self, args: ReadFileArgs) -> ToolResult:
114
+ try:
115
+ target = _resolve_path(args.path)
116
+
117
+ if not target.exists():
118
+ return ToolResult(success=False, error=f"File does not exist: {args.path}")
119
+
120
+ if not target.is_file():
121
+ return ToolResult(success=False, error=f"Path is not a file: {args.path}")
122
+
123
+ # Check file size (limit to 1MB for safety)
124
+ if target.stat().st_size > 1_000_000:
125
+ return ToolResult(
126
+ success=False,
127
+ error=f"File too large ({target.stat().st_size} bytes). Max 1MB."
128
+ )
129
+
130
+ content = target.read_text(encoding="utf-8")
131
+ lines = content.splitlines()
132
+
133
+ # Apply offset and limit
134
+ start = args.offset or 0
135
+ end = start + (args.limit or len(lines))
136
+ selected_lines = lines[start:end]
137
+
138
+ return ToolResult(
139
+ success=True,
140
+ output={
141
+ "path": args.path,
142
+ "content": "\n".join(selected_lines),
143
+ "total_lines": len(lines),
144
+ "start_line": start + 1,
145
+ "end_line": min(end, len(lines)),
146
+ },
147
+ metadata={"size": target.stat().st_size}
148
+ )
149
+ except UnicodeDecodeError:
150
+ return ToolResult(success=False, error="File is not valid UTF-8 text")
151
+ except Exception as e:
152
+ logger.error(f"read_file error: {e}")
153
+ return ToolResult(success=False, error=str(e))
154
+
155
+
156
+ class WriteFileArgs(ToolArgument):
157
+ """Arguments for writing a file."""
158
+ path: str = Field(description="File path to write")
159
+ content: str = Field(description="Content to write")
160
+ create_dirs: bool = Field(default=True, description="Create parent directories if needed")
161
+
162
+
163
+ class WriteFileTool(Tool):
164
+ """Write content to a file."""
165
+
166
+ name = "write_file"
167
+ description = "Create a new file or overwrite an existing file"
168
+ args_schema = WriteFileArgs
169
+ requires_approval = True
170
+
171
+ async def execute(self, args: WriteFileArgs) -> ToolResult:
172
+ try:
173
+ target = _resolve_path(args.path)
174
+
175
+ if args.create_dirs:
176
+ target.parent.mkdir(parents=True, exist_ok=True)
177
+
178
+ target.write_text(args.content, encoding="utf-8")
179
+
180
+ return ToolResult(
181
+ success=True,
182
+ output={"path": args.path, "bytes_written": len(args.content.encode("utf-8"))},
183
+ metadata={"action": "created" if not target.exists() else "overwritten"}
184
+ )
185
+ except Exception as e:
186
+ logger.error(f"write_file error: {e}")
187
+ return ToolResult(success=False, error=str(e))
188
+
189
+
190
+ class EditFileArgs(ToolArgument):
191
+ """Arguments for editing a file."""
192
+ path: str = Field(description="File path to edit")
193
+ old_string: str = Field(description="Exact string to replace")
194
+ new_string: str = Field(description="New string to insert")
195
+ replace_all: bool = Field(default=False, description="Replace all occurrences")
196
+
197
+
198
+ class EditFileTool(Tool):
199
+ """Edit a file by replacing a specific string."""
200
+
201
+ name = "edit_file"
202
+ description = "Make a targeted edit to a file by replacing old_string with new_string"
203
+ args_schema = EditFileArgs
204
+ requires_approval = True
205
+
206
+ async def execute(self, args: EditFileArgs) -> ToolResult:
207
+ try:
208
+ target = _resolve_path(args.path)
209
+
210
+ if not target.exists():
211
+ return ToolResult(success=False, error=f"File does not exist: {args.path}")
212
+
213
+ content = target.read_text(encoding="utf-8")
214
+
215
+ if args.old_string not in content:
216
+ return ToolResult(
217
+ success=False,
218
+ error=f"String not found in file: {args.old_string[:100]}..."
219
+ )
220
+
221
+ if args.replace_all:
222
+ new_content = content.replace(args.old_string, args.new_string)
223
+ count = content.count(args.old_string)
224
+ else:
225
+ count = content.count(args.old_string)
226
+ if count > 1:
227
+ return ToolResult(
228
+ success=False,
229
+ error=f"String appears {count} times. Use replace_all=true or provide more context."
230
+ )
231
+ new_content = content.replace(args.old_string, args.new_string, 1)
232
+
233
+ target.write_text(new_content, encoding="utf-8")
234
+
235
+ return ToolResult(
236
+ success=True,
237
+ output={"path": args.path, "replacements": count},
238
+ metadata={"action": "edited"}
239
+ )
240
+ except Exception as e:
241
+ logger.error(f"edit_file error: {e}")
242
+ return ToolResult(success=False, error=str(e))
243
+
244
+
245
+ class DeleteFileArgs(ToolArgument):
246
+ """Arguments for deleting a file."""
247
+ path: str = Field(description="File or directory path to delete")
248
+ recursive: bool = Field(default=False, description="Delete directories recursively")
249
+
250
+
251
+ class DeleteFileTool(Tool):
252
+ """Delete a file or directory."""
253
+
254
+ name = "delete_file"
255
+ description = "Delete a file or directory"
256
+ args_schema = DeleteFileArgs
257
+ requires_approval = True
258
+ dangerous = True
259
+
260
+ async def execute(self, args: DeleteFileArgs) -> ToolResult:
261
+ try:
262
+ target = _resolve_path(args.path)
263
+
264
+ if not target.exists():
265
+ return ToolResult(success=False, error=f"Path does not exist: {args.path}")
266
+
267
+ if target.is_dir():
268
+ if not args.recursive:
269
+ return ToolResult(success=False, error="Directory not empty. Use recursive=true.")
270
+ import shutil
271
+ shutil.rmtree(target)
272
+ action = "deleted_directory"
273
+ else:
274
+ target.unlink()
275
+ action = "deleted_file"
276
+
277
+ return ToolResult(
278
+ success=True,
279
+ output={"path": args.path},
280
+ metadata={"action": action}
281
+ )
282
+ except Exception as e:
283
+ logger.error(f"delete_file error: {e}")
284
+ return ToolResult(success=False, error=str(e))
285
+
286
+
287
+ class CreateDirectoryArgs(ToolArgument):
288
+ """Arguments for creating a directory."""
289
+ path: str = Field(description="Directory path to create")
290
+ parents: bool = Field(default=True, description="Create parent directories")
291
+
292
+
293
+ class CreateDirectoryTool(Tool):
294
+ """Create a directory."""
295
+
296
+ name = "create_directory"
297
+ description = "Create a new directory"
298
+ args_schema = CreateDirectoryArgs
299
+ requires_approval = True
300
+
301
+ async def execute(self, args: CreateDirectoryArgs) -> ToolResult:
302
+ try:
303
+ target = _resolve_path(args.path)
304
+ target.mkdir(parents=args.parents, exist_ok=True)
305
+
306
+ return ToolResult(
307
+ success=True,
308
+ output={"path": args.path},
309
+ metadata={"action": "created"}
310
+ )
311
+ except Exception as e:
312
+ logger.error(f"create_directory error: {e}")
313
+ return ToolResult(success=False, error=str(e))
314
+
315
+
316
+ # Register all file tools
317
+ register_tool(ListFilesTool())
318
+ register_tool(ReadFileTool())
319
+ register_tool(WriteFileTool())
320
+ register_tool(EditFileTool())
321
+ register_tool(DeleteFileTool())
322
+ register_tool(CreateDirectoryTool())
agent/tools/search.py ADDED
@@ -0,0 +1,223 @@
1
+ """Code search tools for ireri."""
2
+
3
+ import re
4
+ from pathlib import Path
5
+ from typing import Any, Dict, List, Optional
6
+ from pydantic import BaseModel, Field
7
+
8
+ from . import Tool, ToolArgument, ToolResult, register_tool
9
+ from agent.config import get_config
10
+
11
+ import logging
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ def _resolve_path(path: str) -> Path:
17
+ """Resolve a path relative to workspace root."""
18
+ config = get_config()
19
+ workspace = config.workspace_root
20
+
21
+ # Normalize path: handle Unix-style Windows paths like /c/..., /d/...
22
+ # Also handle special paths like /workspace
23
+ normalized_path = path
24
+ if path == "/workspace" or path == "/workspace/":
25
+ normalized_path = "."
26
+ elif path.startswith('/') and len(path) >= 3 and path[2] == '/':
27
+ # Looks like /c/..., /d/... - Unix-style Windows path
28
+ # Strip the leading /c/ and treat as relative
29
+ normalized_path = path[3:]
30
+
31
+ # If the normalized path equals the workspace root path, use "."
32
+ workspace_str = str(workspace).replace('\\', '/')
33
+ if normalized_path == workspace_str or normalized_path == workspace_str.rstrip('/'):
34
+ normalized_path = "."
35
+
36
+ target = (workspace / normalized_path).resolve()
37
+
38
+ try:
39
+ target.relative_to(workspace)
40
+ except ValueError:
41
+ raise ValueError(f"Path '{path}' attempts to escape workspace")
42
+
43
+ return target
44
+
45
+
46
+ class SearchCodeArgs(ToolArgument):
47
+ """Arguments for searching code."""
48
+ pattern: str = Field(description="Regex pattern to search for")
49
+ path: str = Field(default=".", description="Directory to search in")
50
+ file_pattern: Optional[str] = Field(default=None, description="Glob pattern for files (e.g., '*.py')")
51
+ case_sensitive: bool = Field(default=False, description="Case sensitive search")
52
+ max_results: int = Field(default=50, description="Maximum results to return")
53
+
54
+
55
+ class SearchCodeTool(Tool):
56
+ """Search for code patterns in files."""
57
+
58
+ name = "search_code"
59
+ description = "Search for a regex pattern in source files"
60
+ args_schema = SearchCodeArgs
61
+
62
+ async def execute(self, args: SearchCodeArgs) -> ToolResult:
63
+ try:
64
+ target = _resolve_path(args.path)
65
+
66
+ if not target.exists():
67
+ return ToolResult(success=False, error=f"Path does not exist: {args.path}")
68
+
69
+ if not target.is_dir():
70
+ return ToolResult(success=False, error=f"Path is not a directory: {args.path}")
71
+
72
+ # Compile regex
73
+ flags = 0 if args.case_sensitive else re.IGNORECASE
74
+ try:
75
+ regex = re.compile(args.pattern, flags)
76
+ except re.error as e:
77
+ return ToolResult(success=False, error=f"Invalid regex: {e}")
78
+
79
+ results = []
80
+ files_searched = 0
81
+
82
+ # Determine file glob
83
+ glob_pattern = args.file_pattern or "**/*"
84
+
85
+ for file_path in target.rglob(glob_pattern):
86
+ if not file_path.is_file():
87
+ continue
88
+
89
+ # Skip binary files and large files
90
+ try:
91
+ if file_path.stat().st_size > 500_000:
92
+ continue
93
+ except OSError:
94
+ continue
95
+
96
+ files_searched += 1
97
+
98
+ try:
99
+ content = file_path.read_text(encoding="utf-8")
100
+ except UnicodeDecodeError:
101
+ continue # Skip binary files
102
+ except OSError:
103
+ continue
104
+
105
+ lines = content.splitlines()
106
+ for i, line in enumerate(lines):
107
+ matches = list(regex.finditer(line))
108
+ if matches:
109
+ for match in matches:
110
+ rel_path = file_path.relative_to(get_config().workspace_root)
111
+ results.append({
112
+ "file": str(rel_path),
113
+ "line": i + 1,
114
+ "match": line.strip(),
115
+ "span": match.span(),
116
+ })
117
+ if len(results) >= args.max_results:
118
+ break
119
+ if len(results) >= args.max_results:
120
+ break
121
+ if len(results) >= args.max_results:
122
+ break
123
+
124
+ return ToolResult(
125
+ success=True,
126
+ output={
127
+ "results": results,
128
+ "pattern": args.pattern,
129
+ "files_searched": files_searched,
130
+ "total_matches": len(results),
131
+ },
132
+ metadata={"truncated": len(results) >= args.max_results}
133
+ )
134
+ except Exception as e:
135
+ logger.error(f"search_code error: {e}")
136
+ return ToolResult(success=False, error=str(e))
137
+
138
+
139
+ class GetProjectInfoArgs(ToolArgument):
140
+ """Arguments for getting project info."""
141
+ path: str = Field(default=".", description="Project directory path")
142
+
143
+
144
+ class GetProjectInfoTool(Tool):
145
+ """Get project information and structure."""
146
+
147
+ name = "get_project_info"
148
+ description = "Get an overview of the project structure and key files"
149
+ args_schema = GetProjectInfoArgs
150
+
151
+ async def execute(self, args: GetProjectInfoArgs) -> ToolResult:
152
+ try:
153
+ target = _resolve_path(args.path)
154
+
155
+ if not target.exists():
156
+ return ToolResult(success=False, error=f"Path does not exist: {args.path}")
157
+
158
+ info = {
159
+ "root": str(target.relative_to(get_config().workspace_root)),
160
+ "directories": [],
161
+ "files": [],
162
+ "key_files": [],
163
+ "git": False,
164
+ }
165
+
166
+ # Check for git
167
+ if (target / ".git").exists():
168
+ info["git"] = True
169
+
170
+ # Look for key files
171
+ key_patterns = [
172
+ "README*", "package.json", "pyproject.toml", "setup.py",
173
+ "requirements.txt", "Cargo.toml", "go.mod", "pom.xml",
174
+ "tsconfig.json", "vite.config.*", "next.config.*",
175
+ ".env*", "docker-compose*", "Dockerfile",
176
+ ]
177
+
178
+ for item in target.rglob("*"):
179
+ if not item.is_file():
180
+ continue
181
+
182
+ try:
183
+ rel = item.relative_to(target)
184
+ except ValueError:
185
+ continue
186
+
187
+ # Check if it's a key file
188
+ name = item.name
189
+ for pattern in key_patterns:
190
+ if self._match_pattern(name, pattern):
191
+ info["key_files"].append(str(rel))
192
+ break
193
+
194
+ # Limit file listing
195
+ if len(info["files"]) < 100:
196
+ info["files"].append(str(rel))
197
+
198
+ if len(info["key_files"]) >= 20:
199
+ pass # Keep collecting but don't add more
200
+
201
+ # Get directories
202
+ for item in target.iterdir():
203
+ if item.is_dir() and not item.name.startswith("."):
204
+ info["directories"].append(item.name)
205
+
206
+ return ToolResult(
207
+ success=True,
208
+ output=info,
209
+ metadata={}
210
+ )
211
+ except Exception as e:
212
+ logger.error(f"get_project_info error: {e}")
213
+ return ToolResult(success=False, error=str(e))
214
+
215
+ def _match_pattern(self, name: str, pattern: str) -> bool:
216
+ """Simple glob pattern matching."""
217
+ import fnmatch
218
+ return fnmatch.fnmatch(name, pattern)
219
+
220
+
221
+ # Register search tools
222
+ register_tool(SearchCodeTool())
223
+ register_tool(GetProjectInfoTool())