-
-
Notifications
You must be signed in to change notification settings - Fork 2k
feat: filesystem grep, read, edit file #7402
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
Soulter
wants to merge
1
commit into
master
Choose a base branch
from
feat/fs-grep-read-edit
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -9,12 +9,10 @@ | |
| from dataclasses import dataclass | ||
| from typing import Any | ||
|
|
||
| from python_ripgrep import search | ||
|
|
||
| from astrbot.api import logger | ||
| from astrbot.core.utils.astrbot_path import ( | ||
| get_astrbot_data_path, | ||
| get_astrbot_root, | ||
| get_astrbot_temp_path, | ||
| ) | ||
| from astrbot.core.utils.astrbot_path import get_astrbot_root | ||
|
|
||
| from ..olayer import FileSystemComponent, PythonComponent, ShellComponent | ||
| from .base import ComputerBooter | ||
|
|
@@ -41,18 +39,6 @@ def _is_safe_command(command: str) -> bool: | |
| return not any(pat in cmd for pat in _BLOCKED_COMMAND_PATTERNS) | ||
|
|
||
|
|
||
| def _ensure_safe_path(path: str) -> str: | ||
| abs_path = os.path.abspath(path) | ||
| allowed_roots = [ | ||
| os.path.abspath(get_astrbot_root()), | ||
| os.path.abspath(get_astrbot_data_path()), | ||
| os.path.abspath(get_astrbot_temp_path()), | ||
| ] | ||
| if not any(abs_path.startswith(root) for root in allowed_roots): | ||
| raise PermissionError("Path is outside the allowed computer roots.") | ||
| return abs_path | ||
|
|
||
|
|
||
| def _decode_bytes_with_fallback( | ||
| output: bytes | None, | ||
| *, | ||
|
|
@@ -110,7 +96,7 @@ def _run() -> dict[str, Any]: | |
| run_env = os.environ.copy() | ||
| if env: | ||
| run_env.update({str(k): str(v) for k, v in env.items()}) | ||
| working_dir = _ensure_safe_path(cwd) if cwd else get_astrbot_root() | ||
| working_dir = os.path.abspath(cwd) if cwd else get_astrbot_root() | ||
| if background: | ||
| # `command` is intentionally executed through the current shell so | ||
| # local computer-use behavior matches existing tool semantics. | ||
|
|
@@ -186,7 +172,7 @@ async def create_file( | |
| self, path: str, content: str = "", mode: int = 0o644 | ||
| ) -> dict[str, Any]: | ||
| def _run() -> dict[str, Any]: | ||
| abs_path = _ensure_safe_path(path) | ||
| abs_path = os.path.abspath(path) | ||
| os.makedirs(os.path.dirname(abs_path), exist_ok=True) | ||
| with open(abs_path, "w", encoding="utf-8") as f: | ||
| f.write(content) | ||
|
|
@@ -195,24 +181,93 @@ def _run() -> dict[str, Any]: | |
|
|
||
| return await asyncio.to_thread(_run) | ||
|
|
||
| async def read_file(self, path: str, encoding: str = "utf-8") -> dict[str, Any]: | ||
| async def read_file( | ||
| self, | ||
| path: str, | ||
| encoding: str = "utf-8", | ||
| offset: int | None = None, | ||
| limit: int | None = None, | ||
| ) -> dict[str, Any]: | ||
| def _run() -> dict[str, Any]: | ||
| abs_path = _ensure_safe_path(path) | ||
| abs_path = os.path.abspath(path) | ||
| with open(abs_path, "rb") as f: | ||
| raw_content = f.read() | ||
| content = _decode_bytes_with_fallback( | ||
| raw_content, | ||
| preferred_encoding=encoding, | ||
| ) | ||
| return {"success": True, "content": content} | ||
| start = 0 if offset is None else offset | ||
| content_slice = ( | ||
| content[start:] if limit is None else content[start : start + limit] | ||
| ) | ||
| return { | ||
| "success": True, | ||
| "content": content_slice, | ||
| } | ||
|
|
||
| return await asyncio.to_thread(_run) | ||
|
|
||
| async def search_files( | ||
| self, | ||
| pattern: str, | ||
| path: str | None = None, | ||
| glob: str | None = None, | ||
| after_context: int | None = None, | ||
| before_context: int | None = None, | ||
| ) -> dict[str, Any]: | ||
| def _run() -> dict[str, Any]: | ||
| results = search( | ||
| patterns=[pattern], | ||
| paths=[path] if path else None, | ||
| globs=[glob] if glob else None, | ||
| after_context=after_context, | ||
| before_context=before_context, | ||
| line_number=True, | ||
| ) | ||
| return {"success": True, "content": "".join(results)} | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. |
||
|
|
||
| return await asyncio.to_thread(_run) | ||
|
|
||
| async def edit_file( | ||
| self, | ||
| path: str, | ||
| old_string: str, | ||
| new_string: str, | ||
| replace_all: bool = False, | ||
| encoding: str = "utf-8", | ||
| ) -> dict[str, Any]: | ||
| def _run() -> dict[str, Any]: | ||
| abs_path = os.path.abspath(path) | ||
| with open(abs_path, encoding=encoding) as f: | ||
| content = f.read() | ||
|
Comment on lines
+241
to
+242
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. |
||
| occurrences = content.count(old_string) | ||
| if occurrences == 0: | ||
| return { | ||
| "success": False, | ||
| "error": "old string not found in file", | ||
| "replacements": 0, | ||
| } | ||
| if replace_all: | ||
| updated = content.replace(old_string, new_string) | ||
| replacements = occurrences | ||
| else: | ||
| updated = content.replace(old_string, new_string, 1) | ||
| replacements = 1 | ||
| with open(abs_path, "w", encoding=encoding) as f: | ||
| f.write(updated) | ||
| return { | ||
| "success": True, | ||
| "path": abs_path, | ||
| "replacements": replacements, | ||
| } | ||
|
|
||
| return await asyncio.to_thread(_run) | ||
|
|
||
| async def write_file( | ||
| self, path: str, content: str, mode: str = "w", encoding: str = "utf-8" | ||
| ) -> dict[str, Any]: | ||
| def _run() -> dict[str, Any]: | ||
| abs_path = _ensure_safe_path(path) | ||
| abs_path = os.path.abspath(path) | ||
| os.makedirs(os.path.dirname(abs_path), exist_ok=True) | ||
| with open(abs_path, mode, encoding=encoding) as f: | ||
| f.write(content) | ||
|
|
@@ -222,7 +277,7 @@ def _run() -> dict[str, Any]: | |
|
|
||
| async def delete_file(self, path: str) -> dict[str, Any]: | ||
| def _run() -> dict[str, Any]: | ||
| abs_path = _ensure_safe_path(path) | ||
| abs_path = os.path.abspath(path) | ||
| if os.path.isdir(abs_path): | ||
| shutil.rmtree(abs_path) | ||
| else: | ||
|
|
@@ -235,7 +290,7 @@ async def list_dir( | |
| self, path: str = ".", show_hidden: bool = False | ||
| ) -> dict[str, Any]: | ||
| def _run() -> dict[str, Any]: | ||
| abs_path = _ensure_safe_path(path) | ||
| abs_path = os.path.abspath(path) | ||
| entries = os.listdir(abs_path) | ||
| if not show_hidden: | ||
| entries = [e for e in entries if not e.startswith(".")] | ||
|
|
||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Reading the entire file into memory using
f.read()is inefficient and risky for large files, potentially leading to Out-Of-Memory (OOM) errors. Since the tool supportsoffsetandlimit, consider reading the file in chunks or usingf.seek()if the encoding allows, to only load the required portion of the file.