hud-python 0.4.1__py3-none-any.whl → 0.4.3__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.
Potentially problematic release.
This version of hud-python might be problematic. Click here for more details.
- hud/__init__.py +22 -22
- hud/agents/__init__.py +13 -15
- hud/agents/base.py +599 -599
- hud/agents/claude.py +373 -373
- hud/agents/langchain.py +261 -250
- hud/agents/misc/__init__.py +7 -7
- hud/agents/misc/response_agent.py +82 -80
- hud/agents/openai.py +352 -352
- hud/agents/openai_chat_generic.py +154 -154
- hud/agents/tests/__init__.py +1 -1
- hud/agents/tests/test_base.py +742 -742
- hud/agents/tests/test_claude.py +324 -324
- hud/agents/tests/test_client.py +363 -363
- hud/agents/tests/test_openai.py +237 -237
- hud/cli/__init__.py +617 -617
- hud/cli/__main__.py +8 -8
- hud/cli/analyze.py +371 -371
- hud/cli/analyze_metadata.py +230 -230
- hud/cli/build.py +498 -427
- hud/cli/clone.py +185 -185
- hud/cli/cursor.py +92 -92
- hud/cli/debug.py +392 -392
- hud/cli/docker_utils.py +83 -83
- hud/cli/init.py +280 -281
- hud/cli/interactive.py +353 -353
- hud/cli/mcp_server.py +764 -756
- hud/cli/pull.py +330 -336
- hud/cli/push.py +404 -370
- hud/cli/remote_runner.py +311 -311
- hud/cli/runner.py +160 -160
- hud/cli/tests/__init__.py +3 -3
- hud/cli/tests/test_analyze.py +284 -284
- hud/cli/tests/test_cli_init.py +265 -265
- hud/cli/tests/test_cli_main.py +27 -27
- hud/cli/tests/test_clone.py +142 -142
- hud/cli/tests/test_cursor.py +253 -253
- hud/cli/tests/test_debug.py +453 -453
- hud/cli/tests/test_mcp_server.py +139 -139
- hud/cli/tests/test_utils.py +388 -388
- hud/cli/utils.py +263 -263
- hud/clients/README.md +143 -143
- hud/clients/__init__.py +16 -16
- hud/clients/base.py +378 -379
- hud/clients/fastmcp.py +222 -222
- hud/clients/mcp_use.py +298 -278
- hud/clients/tests/__init__.py +1 -1
- hud/clients/tests/test_client_integration.py +111 -111
- hud/clients/tests/test_fastmcp.py +342 -342
- hud/clients/tests/test_protocol.py +188 -188
- hud/clients/utils/__init__.py +1 -1
- hud/clients/utils/retry_transport.py +160 -160
- hud/datasets.py +327 -322
- hud/misc/__init__.py +1 -1
- hud/misc/claude_plays_pokemon.py +292 -292
- hud/otel/__init__.py +35 -35
- hud/otel/collector.py +142 -142
- hud/otel/config.py +164 -164
- hud/otel/context.py +536 -536
- hud/otel/exporters.py +366 -366
- hud/otel/instrumentation.py +97 -97
- hud/otel/processors.py +118 -118
- hud/otel/tests/__init__.py +1 -1
- hud/otel/tests/test_processors.py +197 -197
- hud/server/__init__.py +5 -5
- hud/server/context.py +114 -114
- hud/server/helper/__init__.py +5 -5
- hud/server/low_level.py +132 -132
- hud/server/server.py +170 -166
- hud/server/tests/__init__.py +3 -3
- hud/settings.py +73 -73
- hud/shared/__init__.py +5 -5
- hud/shared/exceptions.py +180 -180
- hud/shared/requests.py +264 -264
- hud/shared/tests/test_exceptions.py +157 -157
- hud/shared/tests/test_requests.py +275 -275
- hud/telemetry/__init__.py +25 -25
- hud/telemetry/instrument.py +379 -379
- hud/telemetry/job.py +309 -309
- hud/telemetry/replay.py +74 -74
- hud/telemetry/trace.py +83 -83
- hud/tools/__init__.py +33 -33
- hud/tools/base.py +365 -365
- hud/tools/bash.py +161 -161
- hud/tools/computer/__init__.py +15 -15
- hud/tools/computer/anthropic.py +437 -437
- hud/tools/computer/hud.py +376 -376
- hud/tools/computer/openai.py +295 -295
- hud/tools/computer/settings.py +82 -82
- hud/tools/edit.py +314 -314
- hud/tools/executors/__init__.py +30 -30
- hud/tools/executors/base.py +539 -539
- hud/tools/executors/pyautogui.py +621 -621
- hud/tools/executors/tests/__init__.py +1 -1
- hud/tools/executors/tests/test_base_executor.py +338 -338
- hud/tools/executors/tests/test_pyautogui_executor.py +165 -165
- hud/tools/executors/xdo.py +511 -511
- hud/tools/playwright.py +412 -412
- hud/tools/tests/__init__.py +3 -3
- hud/tools/tests/test_base.py +282 -282
- hud/tools/tests/test_bash.py +158 -158
- hud/tools/tests/test_bash_extended.py +197 -197
- hud/tools/tests/test_computer.py +425 -425
- hud/tools/tests/test_computer_actions.py +34 -34
- hud/tools/tests/test_edit.py +259 -259
- hud/tools/tests/test_init.py +27 -27
- hud/tools/tests/test_playwright_tool.py +183 -183
- hud/tools/tests/test_tools.py +145 -145
- hud/tools/tests/test_utils.py +156 -156
- hud/tools/types.py +72 -72
- hud/tools/utils.py +50 -50
- hud/types.py +136 -136
- hud/utils/__init__.py +10 -10
- hud/utils/async_utils.py +65 -65
- hud/utils/design.py +236 -168
- hud/utils/mcp.py +55 -55
- hud/utils/progress.py +149 -149
- hud/utils/telemetry.py +66 -66
- hud/utils/tests/test_async_utils.py +173 -173
- hud/utils/tests/test_init.py +17 -17
- hud/utils/tests/test_progress.py +261 -261
- hud/utils/tests/test_telemetry.py +82 -82
- hud/utils/tests/test_version.py +8 -8
- hud/version.py +7 -7
- {hud_python-0.4.1.dist-info → hud_python-0.4.3.dist-info}/METADATA +10 -8
- hud_python-0.4.3.dist-info/RECORD +131 -0
- {hud_python-0.4.1.dist-info → hud_python-0.4.3.dist-info}/licenses/LICENSE +21 -21
- hud/agents/art.py +0 -101
- hud_python-0.4.1.dist-info/RECORD +0 -132
- {hud_python-0.4.1.dist-info → hud_python-0.4.3.dist-info}/WHEEL +0 -0
- {hud_python-0.4.1.dist-info → hud_python-0.4.3.dist-info}/entry_points.txt +0 -0
hud/tools/edit.py
CHANGED
|
@@ -1,314 +1,314 @@
|
|
|
1
|
-
from __future__ import annotations
|
|
2
|
-
|
|
3
|
-
from collections import defaultdict
|
|
4
|
-
from pathlib import Path
|
|
5
|
-
from typing import TYPE_CHECKING, Any, Literal, get_args
|
|
6
|
-
|
|
7
|
-
from .base import BaseTool
|
|
8
|
-
from .types import ContentResult, ToolError
|
|
9
|
-
from .utils import maybe_truncate, run
|
|
10
|
-
|
|
11
|
-
if TYPE_CHECKING:
|
|
12
|
-
from mcp.types import ContentBlock
|
|
13
|
-
|
|
14
|
-
Command = Literal[
|
|
15
|
-
"view",
|
|
16
|
-
"create",
|
|
17
|
-
"str_replace",
|
|
18
|
-
"insert",
|
|
19
|
-
"undo_edit",
|
|
20
|
-
]
|
|
21
|
-
SNIPPET_LINES: int = 4
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
class EditTool(BaseTool):
|
|
25
|
-
"""
|
|
26
|
-
A filesystem editor tool that allows the agent to view, create, and edit files.
|
|
27
|
-
Maintains a history of file edits for undo functionality.
|
|
28
|
-
"""
|
|
29
|
-
|
|
30
|
-
def __init__(self, file_history: dict[Path, list[str]] | None = None) -> None:
|
|
31
|
-
"""Initialize EditTool with optional file history.
|
|
32
|
-
|
|
33
|
-
Args:
|
|
34
|
-
file_history: Optional dictionary tracking edit history per file.
|
|
35
|
-
If not provided, a new history will be created.
|
|
36
|
-
"""
|
|
37
|
-
super().__init__(
|
|
38
|
-
env=file_history or defaultdict(list),
|
|
39
|
-
name="edit",
|
|
40
|
-
title="File Editor",
|
|
41
|
-
description="View, create, and edit files with undo support",
|
|
42
|
-
)
|
|
43
|
-
|
|
44
|
-
@property
|
|
45
|
-
def file_history(self) -> dict[Path, list[str]]:
|
|
46
|
-
"""Get the file edit history (alias for context)."""
|
|
47
|
-
return self.env
|
|
48
|
-
|
|
49
|
-
async def __call__(
|
|
50
|
-
self,
|
|
51
|
-
*,
|
|
52
|
-
command: Command,
|
|
53
|
-
path: str,
|
|
54
|
-
file_text: str | None = None,
|
|
55
|
-
view_range: list[int] | None = None,
|
|
56
|
-
old_str: str | None = None,
|
|
57
|
-
new_str: str | None = None,
|
|
58
|
-
insert_line: int | None = None,
|
|
59
|
-
**kwargs: Any,
|
|
60
|
-
) -> list[ContentBlock]:
|
|
61
|
-
_path = Path(path)
|
|
62
|
-
self.validate_path(command, _path)
|
|
63
|
-
if command == "view":
|
|
64
|
-
result = await self.view(_path, view_range)
|
|
65
|
-
return result.to_content_blocks()
|
|
66
|
-
elif command == "create":
|
|
67
|
-
if file_text is None:
|
|
68
|
-
raise ToolError("Parameter `file_text` is required for command: create")
|
|
69
|
-
await self.write_file(_path, file_text)
|
|
70
|
-
self.file_history[_path].append(file_text)
|
|
71
|
-
return ContentResult(
|
|
72
|
-
output=f"File created successfully at: {_path}"
|
|
73
|
-
).to_content_blocks()
|
|
74
|
-
elif command == "str_replace":
|
|
75
|
-
if old_str is None:
|
|
76
|
-
raise ToolError("Parameter `old_str` is required for command: str_replace")
|
|
77
|
-
result = await self.str_replace(_path, old_str, new_str)
|
|
78
|
-
return result.to_content_blocks()
|
|
79
|
-
elif command == "insert":
|
|
80
|
-
if insert_line is None:
|
|
81
|
-
raise ToolError("Parameter `insert_line` is required for command: insert")
|
|
82
|
-
if new_str is None:
|
|
83
|
-
raise ToolError("Parameter `new_str` is required for command: insert")
|
|
84
|
-
result = await self.insert(_path, insert_line, new_str)
|
|
85
|
-
return result.to_content_blocks()
|
|
86
|
-
elif command == "undo_edit":
|
|
87
|
-
result = await self.undo_edit(_path)
|
|
88
|
-
return result.to_content_blocks()
|
|
89
|
-
raise ToolError(
|
|
90
|
-
f"Unrecognized command {command}. The allowed commands for the {self.name} tool are: "
|
|
91
|
-
f"{', '.join(get_args(Command))}"
|
|
92
|
-
)
|
|
93
|
-
|
|
94
|
-
def validate_path(self, command: str, path: Path) -> None:
|
|
95
|
-
"""
|
|
96
|
-
Check that the path/command combination is valid.
|
|
97
|
-
"""
|
|
98
|
-
# Check if its an absolute path
|
|
99
|
-
if not path.is_absolute():
|
|
100
|
-
suggested_path = Path("") / path
|
|
101
|
-
raise ToolError(
|
|
102
|
-
f"The path {path} is not an absolute path, it should start with `/`. "
|
|
103
|
-
f"Maybe you meant {suggested_path}?"
|
|
104
|
-
)
|
|
105
|
-
# Check if path exists
|
|
106
|
-
if not path.exists() and command != "create":
|
|
107
|
-
raise ToolError(f"The path {path} does not exist. Please provide a valid path.")
|
|
108
|
-
if path.exists() and command == "create":
|
|
109
|
-
raise ToolError(
|
|
110
|
-
f"File already exists at: {path}. Cannot overwrite files using command `create`."
|
|
111
|
-
)
|
|
112
|
-
# Check if the path points to a directory
|
|
113
|
-
if path.is_dir() and command != "view":
|
|
114
|
-
raise ToolError(
|
|
115
|
-
f"The path {path} is a dir and only the `view` command can be used on dirs."
|
|
116
|
-
)
|
|
117
|
-
|
|
118
|
-
async def view(self, path: Path, view_range: list[int] | None = None) -> ContentResult:
|
|
119
|
-
"""Implement the view command"""
|
|
120
|
-
if path.is_dir():
|
|
121
|
-
if view_range:
|
|
122
|
-
raise ToolError(
|
|
123
|
-
"The `view_range` parameter is not allowed when `path` points to a directory."
|
|
124
|
-
)
|
|
125
|
-
|
|
126
|
-
import shlex
|
|
127
|
-
|
|
128
|
-
safe_path = shlex.quote(str(path))
|
|
129
|
-
_, stdout, stderr = await run(rf"find {safe_path} -maxdepth 2 -not -path '*/\.*'")
|
|
130
|
-
if not stderr:
|
|
131
|
-
stdout = (
|
|
132
|
-
f"Here's the files and directories up to 2 levels deep in {path}, "
|
|
133
|
-
f"excluding hidden items:\n{stdout}\n"
|
|
134
|
-
)
|
|
135
|
-
return ContentResult(output=stdout, error=stderr)
|
|
136
|
-
|
|
137
|
-
file_content = await self.read_file(path)
|
|
138
|
-
init_line = 1
|
|
139
|
-
if view_range:
|
|
140
|
-
if len(view_range) != 2 or not all(isinstance(i, int) for i in view_range):
|
|
141
|
-
raise ToolError("Invalid `view_range`. It should be a list of two integers.")
|
|
142
|
-
file_lines = file_content.split("\n")
|
|
143
|
-
n_lines_file = len(file_lines)
|
|
144
|
-
init_line, final_line = view_range
|
|
145
|
-
if init_line < 1 or init_line > n_lines_file:
|
|
146
|
-
raise ToolError(
|
|
147
|
-
f"Invalid `view_range`: {view_range}. Its first element `{init_line}` "
|
|
148
|
-
f"should be within the range of lines of the file: {[1, n_lines_file]}"
|
|
149
|
-
)
|
|
150
|
-
if final_line > n_lines_file:
|
|
151
|
-
raise ToolError(
|
|
152
|
-
f"Invalid `view_range`: {view_range}. Its second element `{final_line}` "
|
|
153
|
-
f"should be smaller than the number of lines in the file: `{n_lines_file}`"
|
|
154
|
-
)
|
|
155
|
-
if final_line != -1 and final_line < init_line:
|
|
156
|
-
raise ToolError(
|
|
157
|
-
f"Invalid `view_range`: {view_range}. Its second element `{final_line}` "
|
|
158
|
-
f"should be larger or equal than its first `{init_line}`"
|
|
159
|
-
)
|
|
160
|
-
|
|
161
|
-
if final_line == -1:
|
|
162
|
-
file_content = "\n".join(file_lines[init_line - 1 :])
|
|
163
|
-
else:
|
|
164
|
-
file_content = "\n".join(file_lines[init_line - 1 : final_line])
|
|
165
|
-
|
|
166
|
-
return ContentResult(output=self._make_output(file_content, str(path), init_line=init_line))
|
|
167
|
-
|
|
168
|
-
async def str_replace(self, path: Path, old_str: str, new_str: str | None) -> ContentResult:
|
|
169
|
-
"""
|
|
170
|
-
Implement the str_replace command, which replaces old_str with new_str in the file content.
|
|
171
|
-
"""
|
|
172
|
-
# Read the file content
|
|
173
|
-
file_content = (await self.read_file(path)).expandtabs()
|
|
174
|
-
old_str = old_str.expandtabs()
|
|
175
|
-
new_str = new_str.expandtabs() if new_str is not None else ""
|
|
176
|
-
|
|
177
|
-
# Check if old_str is unique in the file
|
|
178
|
-
occurrences = file_content.count(old_str)
|
|
179
|
-
if occurrences == 0:
|
|
180
|
-
raise ToolError(
|
|
181
|
-
f"No replacement was performed, old_str `{old_str}` did not appear verbatim in "
|
|
182
|
-
f"{path}."
|
|
183
|
-
)
|
|
184
|
-
elif occurrences > 1:
|
|
185
|
-
file_content_lines = file_content.split("\n")
|
|
186
|
-
lines = [idx + 1 for idx, line in enumerate(file_content_lines) if old_str in line]
|
|
187
|
-
raise ToolError(
|
|
188
|
-
f"No replacement was performed. Multiple occurrences of old_str `{old_str}` "
|
|
189
|
-
f"in lines {lines}. Please ensure it is unique"
|
|
190
|
-
)
|
|
191
|
-
|
|
192
|
-
# Replace old_str with new_str
|
|
193
|
-
new_file_content = file_content.replace(old_str, new_str)
|
|
194
|
-
|
|
195
|
-
# Write the new content to the file
|
|
196
|
-
await self.write_file(path, new_file_content)
|
|
197
|
-
|
|
198
|
-
# Save the content to history
|
|
199
|
-
self.file_history[path].append(file_content)
|
|
200
|
-
|
|
201
|
-
# Create a snippet of the edited section
|
|
202
|
-
replacement_line = file_content.split(old_str)[0].count("\n")
|
|
203
|
-
start_line = max(0, replacement_line - SNIPPET_LINES)
|
|
204
|
-
end_line = replacement_line + SNIPPET_LINES + new_str.count("\n")
|
|
205
|
-
snippet = "\n".join(new_file_content.split("\n")[start_line : end_line + 1])
|
|
206
|
-
|
|
207
|
-
# Prepare the success message
|
|
208
|
-
success_msg = f"The file {path} has been edited. "
|
|
209
|
-
success_msg += self._make_output(snippet, f"a snippet of {path}", start_line + 1)
|
|
210
|
-
success_msg += (
|
|
211
|
-
"Review the changes and make sure they are as expected. "
|
|
212
|
-
"Edit the file again if necessary."
|
|
213
|
-
)
|
|
214
|
-
|
|
215
|
-
return ContentResult(output=success_msg)
|
|
216
|
-
|
|
217
|
-
async def insert(self, path: Path, insert_line: int, new_str: str) -> ContentResult:
|
|
218
|
-
"""
|
|
219
|
-
Implement the insert command, which inserts new_str at the specified line in the file.
|
|
220
|
-
"""
|
|
221
|
-
file_text = (await self.read_file(path)).expandtabs()
|
|
222
|
-
new_str = new_str.expandtabs()
|
|
223
|
-
file_text_lines = file_text.split("\n")
|
|
224
|
-
n_lines_file = len(file_text_lines)
|
|
225
|
-
|
|
226
|
-
if insert_line < 0 or insert_line > n_lines_file:
|
|
227
|
-
raise ToolError(
|
|
228
|
-
f"Invalid `insert_line` parameter: {insert_line}. It should be within the range "
|
|
229
|
-
f"of lines of the file: {[0, n_lines_file]}"
|
|
230
|
-
)
|
|
231
|
-
|
|
232
|
-
new_str_lines = new_str.split("\n")
|
|
233
|
-
new_file_text_lines = (
|
|
234
|
-
file_text_lines[:insert_line] + new_str_lines + file_text_lines[insert_line:]
|
|
235
|
-
)
|
|
236
|
-
snippet_lines = (
|
|
237
|
-
file_text_lines[max(0, insert_line - SNIPPET_LINES) : insert_line]
|
|
238
|
-
+ new_str_lines
|
|
239
|
-
+ file_text_lines[insert_line : insert_line + SNIPPET_LINES]
|
|
240
|
-
)
|
|
241
|
-
|
|
242
|
-
new_file_text = "\n".join(new_file_text_lines)
|
|
243
|
-
snippet = "\n".join(snippet_lines)
|
|
244
|
-
|
|
245
|
-
await self.write_file(path, new_file_text)
|
|
246
|
-
self.file_history[path].append(file_text)
|
|
247
|
-
|
|
248
|
-
success_msg = f"The file {path} has been edited. "
|
|
249
|
-
success_msg += self._make_output(
|
|
250
|
-
snippet,
|
|
251
|
-
"a snippet of the edited file",
|
|
252
|
-
max(1, insert_line - SNIPPET_LINES + 1),
|
|
253
|
-
)
|
|
254
|
-
success_msg += (
|
|
255
|
-
"Review the changes and make sure they are as expected (correct indentation, "
|
|
256
|
-
"no duplicate lines, etc). Edit the file again if necessary."
|
|
257
|
-
)
|
|
258
|
-
return ContentResult(output=success_msg)
|
|
259
|
-
|
|
260
|
-
async def undo_edit(self, path: Path) -> ContentResult:
|
|
261
|
-
"""Implement the undo_edit command."""
|
|
262
|
-
if not self.file_history[path]:
|
|
263
|
-
raise ToolError(f"No edit history found for {path}.")
|
|
264
|
-
|
|
265
|
-
old_text = self.file_history[path].pop()
|
|
266
|
-
await self.write_file(path, old_text)
|
|
267
|
-
|
|
268
|
-
return ContentResult(
|
|
269
|
-
output=f"Last edit to {path} undone successfully. "
|
|
270
|
-
f"{self._make_output(old_text, str(path))}"
|
|
271
|
-
)
|
|
272
|
-
|
|
273
|
-
async def read_file(self, path: Path) -> str:
|
|
274
|
-
"""Read the content of a file from a given path; raise a ToolError if an error occurs."""
|
|
275
|
-
try:
|
|
276
|
-
import shlex
|
|
277
|
-
|
|
278
|
-
safe_path = shlex.quote(str(path))
|
|
279
|
-
code, out, err = await run(f"cat {safe_path}")
|
|
280
|
-
if code != 0:
|
|
281
|
-
raise ToolError(f"Ran into {err} while trying to read {path}")
|
|
282
|
-
return out
|
|
283
|
-
except Exception as e:
|
|
284
|
-
raise ToolError(f"Ran into {e} while trying to read {path}") from None
|
|
285
|
-
|
|
286
|
-
async def write_file(self, path: Path, file: str) -> None:
|
|
287
|
-
"""Write the content of a file to a given path; raise a ToolError if an error occurs."""
|
|
288
|
-
try:
|
|
289
|
-
import shlex
|
|
290
|
-
|
|
291
|
-
safe_path = shlex.quote(str(path))
|
|
292
|
-
code, _, err = await run(f"cat > {safe_path} << 'EOF'\n{file}\nEOF")
|
|
293
|
-
if code != 0:
|
|
294
|
-
raise ToolError(f"Ran into {err} while trying to write to {path}")
|
|
295
|
-
except Exception as e:
|
|
296
|
-
raise ToolError(f"Ran into {e} while trying to write to {path}") from None
|
|
297
|
-
|
|
298
|
-
def _make_output(
|
|
299
|
-
self,
|
|
300
|
-
file_content: str,
|
|
301
|
-
file_descriptor: str,
|
|
302
|
-
init_line: int = 1,
|
|
303
|
-
expand_tabs: bool = True,
|
|
304
|
-
) -> str:
|
|
305
|
-
"""Generate output for the CLI based on the content of a file."""
|
|
306
|
-
file_content = maybe_truncate(file_content)
|
|
307
|
-
if expand_tabs:
|
|
308
|
-
file_content = file_content.expandtabs()
|
|
309
|
-
file_content = "\n".join(
|
|
310
|
-
[f"{i + init_line:6}\t{line}" for i, line in enumerate(file_content.split("\n"))]
|
|
311
|
-
)
|
|
312
|
-
return (
|
|
313
|
-
f"Here's the result of running `cat -n` on {file_descriptor}:\n" + file_content + "\n"
|
|
314
|
-
)
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections import defaultdict
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import TYPE_CHECKING, Any, Literal, get_args
|
|
6
|
+
|
|
7
|
+
from .base import BaseTool
|
|
8
|
+
from .types import ContentResult, ToolError
|
|
9
|
+
from .utils import maybe_truncate, run
|
|
10
|
+
|
|
11
|
+
if TYPE_CHECKING:
|
|
12
|
+
from mcp.types import ContentBlock
|
|
13
|
+
|
|
14
|
+
Command = Literal[
|
|
15
|
+
"view",
|
|
16
|
+
"create",
|
|
17
|
+
"str_replace",
|
|
18
|
+
"insert",
|
|
19
|
+
"undo_edit",
|
|
20
|
+
]
|
|
21
|
+
SNIPPET_LINES: int = 4
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class EditTool(BaseTool):
|
|
25
|
+
"""
|
|
26
|
+
A filesystem editor tool that allows the agent to view, create, and edit files.
|
|
27
|
+
Maintains a history of file edits for undo functionality.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
def __init__(self, file_history: dict[Path, list[str]] | None = None) -> None:
|
|
31
|
+
"""Initialize EditTool with optional file history.
|
|
32
|
+
|
|
33
|
+
Args:
|
|
34
|
+
file_history: Optional dictionary tracking edit history per file.
|
|
35
|
+
If not provided, a new history will be created.
|
|
36
|
+
"""
|
|
37
|
+
super().__init__(
|
|
38
|
+
env=file_history or defaultdict(list),
|
|
39
|
+
name="edit",
|
|
40
|
+
title="File Editor",
|
|
41
|
+
description="View, create, and edit files with undo support",
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
@property
|
|
45
|
+
def file_history(self) -> dict[Path, list[str]]:
|
|
46
|
+
"""Get the file edit history (alias for context)."""
|
|
47
|
+
return self.env
|
|
48
|
+
|
|
49
|
+
async def __call__(
|
|
50
|
+
self,
|
|
51
|
+
*,
|
|
52
|
+
command: Command,
|
|
53
|
+
path: str,
|
|
54
|
+
file_text: str | None = None,
|
|
55
|
+
view_range: list[int] | None = None,
|
|
56
|
+
old_str: str | None = None,
|
|
57
|
+
new_str: str | None = None,
|
|
58
|
+
insert_line: int | None = None,
|
|
59
|
+
**kwargs: Any,
|
|
60
|
+
) -> list[ContentBlock]:
|
|
61
|
+
_path = Path(path)
|
|
62
|
+
self.validate_path(command, _path)
|
|
63
|
+
if command == "view":
|
|
64
|
+
result = await self.view(_path, view_range)
|
|
65
|
+
return result.to_content_blocks()
|
|
66
|
+
elif command == "create":
|
|
67
|
+
if file_text is None:
|
|
68
|
+
raise ToolError("Parameter `file_text` is required for command: create")
|
|
69
|
+
await self.write_file(_path, file_text)
|
|
70
|
+
self.file_history[_path].append(file_text)
|
|
71
|
+
return ContentResult(
|
|
72
|
+
output=f"File created successfully at: {_path}"
|
|
73
|
+
).to_content_blocks()
|
|
74
|
+
elif command == "str_replace":
|
|
75
|
+
if old_str is None:
|
|
76
|
+
raise ToolError("Parameter `old_str` is required for command: str_replace")
|
|
77
|
+
result = await self.str_replace(_path, old_str, new_str)
|
|
78
|
+
return result.to_content_blocks()
|
|
79
|
+
elif command == "insert":
|
|
80
|
+
if insert_line is None:
|
|
81
|
+
raise ToolError("Parameter `insert_line` is required for command: insert")
|
|
82
|
+
if new_str is None:
|
|
83
|
+
raise ToolError("Parameter `new_str` is required for command: insert")
|
|
84
|
+
result = await self.insert(_path, insert_line, new_str)
|
|
85
|
+
return result.to_content_blocks()
|
|
86
|
+
elif command == "undo_edit":
|
|
87
|
+
result = await self.undo_edit(_path)
|
|
88
|
+
return result.to_content_blocks()
|
|
89
|
+
raise ToolError(
|
|
90
|
+
f"Unrecognized command {command}. The allowed commands for the {self.name} tool are: "
|
|
91
|
+
f"{', '.join(get_args(Command))}"
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
def validate_path(self, command: str, path: Path) -> None:
|
|
95
|
+
"""
|
|
96
|
+
Check that the path/command combination is valid.
|
|
97
|
+
"""
|
|
98
|
+
# Check if its an absolute path
|
|
99
|
+
if not path.is_absolute():
|
|
100
|
+
suggested_path = Path("") / path
|
|
101
|
+
raise ToolError(
|
|
102
|
+
f"The path {path} is not an absolute path, it should start with `/`. "
|
|
103
|
+
f"Maybe you meant {suggested_path}?"
|
|
104
|
+
)
|
|
105
|
+
# Check if path exists
|
|
106
|
+
if not path.exists() and command != "create":
|
|
107
|
+
raise ToolError(f"The path {path} does not exist. Please provide a valid path.")
|
|
108
|
+
if path.exists() and command == "create":
|
|
109
|
+
raise ToolError(
|
|
110
|
+
f"File already exists at: {path}. Cannot overwrite files using command `create`."
|
|
111
|
+
)
|
|
112
|
+
# Check if the path points to a directory
|
|
113
|
+
if path.is_dir() and command != "view":
|
|
114
|
+
raise ToolError(
|
|
115
|
+
f"The path {path} is a dir and only the `view` command can be used on dirs."
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
async def view(self, path: Path, view_range: list[int] | None = None) -> ContentResult:
|
|
119
|
+
"""Implement the view command"""
|
|
120
|
+
if path.is_dir():
|
|
121
|
+
if view_range:
|
|
122
|
+
raise ToolError(
|
|
123
|
+
"The `view_range` parameter is not allowed when `path` points to a directory."
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
import shlex
|
|
127
|
+
|
|
128
|
+
safe_path = shlex.quote(str(path))
|
|
129
|
+
_, stdout, stderr = await run(rf"find {safe_path} -maxdepth 2 -not -path '*/\.*'")
|
|
130
|
+
if not stderr:
|
|
131
|
+
stdout = (
|
|
132
|
+
f"Here's the files and directories up to 2 levels deep in {path}, "
|
|
133
|
+
f"excluding hidden items:\n{stdout}\n"
|
|
134
|
+
)
|
|
135
|
+
return ContentResult(output=stdout, error=stderr)
|
|
136
|
+
|
|
137
|
+
file_content = await self.read_file(path)
|
|
138
|
+
init_line = 1
|
|
139
|
+
if view_range:
|
|
140
|
+
if len(view_range) != 2 or not all(isinstance(i, int) for i in view_range):
|
|
141
|
+
raise ToolError("Invalid `view_range`. It should be a list of two integers.")
|
|
142
|
+
file_lines = file_content.split("\n")
|
|
143
|
+
n_lines_file = len(file_lines)
|
|
144
|
+
init_line, final_line = view_range
|
|
145
|
+
if init_line < 1 or init_line > n_lines_file:
|
|
146
|
+
raise ToolError(
|
|
147
|
+
f"Invalid `view_range`: {view_range}. Its first element `{init_line}` "
|
|
148
|
+
f"should be within the range of lines of the file: {[1, n_lines_file]}"
|
|
149
|
+
)
|
|
150
|
+
if final_line > n_lines_file:
|
|
151
|
+
raise ToolError(
|
|
152
|
+
f"Invalid `view_range`: {view_range}. Its second element `{final_line}` "
|
|
153
|
+
f"should be smaller than the number of lines in the file: `{n_lines_file}`"
|
|
154
|
+
)
|
|
155
|
+
if final_line != -1 and final_line < init_line:
|
|
156
|
+
raise ToolError(
|
|
157
|
+
f"Invalid `view_range`: {view_range}. Its second element `{final_line}` "
|
|
158
|
+
f"should be larger or equal than its first `{init_line}`"
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
if final_line == -1:
|
|
162
|
+
file_content = "\n".join(file_lines[init_line - 1 :])
|
|
163
|
+
else:
|
|
164
|
+
file_content = "\n".join(file_lines[init_line - 1 : final_line])
|
|
165
|
+
|
|
166
|
+
return ContentResult(output=self._make_output(file_content, str(path), init_line=init_line))
|
|
167
|
+
|
|
168
|
+
async def str_replace(self, path: Path, old_str: str, new_str: str | None) -> ContentResult:
|
|
169
|
+
"""
|
|
170
|
+
Implement the str_replace command, which replaces old_str with new_str in the file content.
|
|
171
|
+
"""
|
|
172
|
+
# Read the file content
|
|
173
|
+
file_content = (await self.read_file(path)).expandtabs()
|
|
174
|
+
old_str = old_str.expandtabs()
|
|
175
|
+
new_str = new_str.expandtabs() if new_str is not None else ""
|
|
176
|
+
|
|
177
|
+
# Check if old_str is unique in the file
|
|
178
|
+
occurrences = file_content.count(old_str)
|
|
179
|
+
if occurrences == 0:
|
|
180
|
+
raise ToolError(
|
|
181
|
+
f"No replacement was performed, old_str `{old_str}` did not appear verbatim in "
|
|
182
|
+
f"{path}."
|
|
183
|
+
)
|
|
184
|
+
elif occurrences > 1:
|
|
185
|
+
file_content_lines = file_content.split("\n")
|
|
186
|
+
lines = [idx + 1 for idx, line in enumerate(file_content_lines) if old_str in line]
|
|
187
|
+
raise ToolError(
|
|
188
|
+
f"No replacement was performed. Multiple occurrences of old_str `{old_str}` "
|
|
189
|
+
f"in lines {lines}. Please ensure it is unique"
|
|
190
|
+
)
|
|
191
|
+
|
|
192
|
+
# Replace old_str with new_str
|
|
193
|
+
new_file_content = file_content.replace(old_str, new_str)
|
|
194
|
+
|
|
195
|
+
# Write the new content to the file
|
|
196
|
+
await self.write_file(path, new_file_content)
|
|
197
|
+
|
|
198
|
+
# Save the content to history
|
|
199
|
+
self.file_history[path].append(file_content)
|
|
200
|
+
|
|
201
|
+
# Create a snippet of the edited section
|
|
202
|
+
replacement_line = file_content.split(old_str)[0].count("\n")
|
|
203
|
+
start_line = max(0, replacement_line - SNIPPET_LINES)
|
|
204
|
+
end_line = replacement_line + SNIPPET_LINES + new_str.count("\n")
|
|
205
|
+
snippet = "\n".join(new_file_content.split("\n")[start_line : end_line + 1])
|
|
206
|
+
|
|
207
|
+
# Prepare the success message
|
|
208
|
+
success_msg = f"The file {path} has been edited. "
|
|
209
|
+
success_msg += self._make_output(snippet, f"a snippet of {path}", start_line + 1)
|
|
210
|
+
success_msg += (
|
|
211
|
+
"Review the changes and make sure they are as expected. "
|
|
212
|
+
"Edit the file again if necessary."
|
|
213
|
+
)
|
|
214
|
+
|
|
215
|
+
return ContentResult(output=success_msg)
|
|
216
|
+
|
|
217
|
+
async def insert(self, path: Path, insert_line: int, new_str: str) -> ContentResult:
|
|
218
|
+
"""
|
|
219
|
+
Implement the insert command, which inserts new_str at the specified line in the file.
|
|
220
|
+
"""
|
|
221
|
+
file_text = (await self.read_file(path)).expandtabs()
|
|
222
|
+
new_str = new_str.expandtabs()
|
|
223
|
+
file_text_lines = file_text.split("\n")
|
|
224
|
+
n_lines_file = len(file_text_lines)
|
|
225
|
+
|
|
226
|
+
if insert_line < 0 or insert_line > n_lines_file:
|
|
227
|
+
raise ToolError(
|
|
228
|
+
f"Invalid `insert_line` parameter: {insert_line}. It should be within the range "
|
|
229
|
+
f"of lines of the file: {[0, n_lines_file]}"
|
|
230
|
+
)
|
|
231
|
+
|
|
232
|
+
new_str_lines = new_str.split("\n")
|
|
233
|
+
new_file_text_lines = (
|
|
234
|
+
file_text_lines[:insert_line] + new_str_lines + file_text_lines[insert_line:]
|
|
235
|
+
)
|
|
236
|
+
snippet_lines = (
|
|
237
|
+
file_text_lines[max(0, insert_line - SNIPPET_LINES) : insert_line]
|
|
238
|
+
+ new_str_lines
|
|
239
|
+
+ file_text_lines[insert_line : insert_line + SNIPPET_LINES]
|
|
240
|
+
)
|
|
241
|
+
|
|
242
|
+
new_file_text = "\n".join(new_file_text_lines)
|
|
243
|
+
snippet = "\n".join(snippet_lines)
|
|
244
|
+
|
|
245
|
+
await self.write_file(path, new_file_text)
|
|
246
|
+
self.file_history[path].append(file_text)
|
|
247
|
+
|
|
248
|
+
success_msg = f"The file {path} has been edited. "
|
|
249
|
+
success_msg += self._make_output(
|
|
250
|
+
snippet,
|
|
251
|
+
"a snippet of the edited file",
|
|
252
|
+
max(1, insert_line - SNIPPET_LINES + 1),
|
|
253
|
+
)
|
|
254
|
+
success_msg += (
|
|
255
|
+
"Review the changes and make sure they are as expected (correct indentation, "
|
|
256
|
+
"no duplicate lines, etc). Edit the file again if necessary."
|
|
257
|
+
)
|
|
258
|
+
return ContentResult(output=success_msg)
|
|
259
|
+
|
|
260
|
+
async def undo_edit(self, path: Path) -> ContentResult:
|
|
261
|
+
"""Implement the undo_edit command."""
|
|
262
|
+
if not self.file_history[path]:
|
|
263
|
+
raise ToolError(f"No edit history found for {path}.")
|
|
264
|
+
|
|
265
|
+
old_text = self.file_history[path].pop()
|
|
266
|
+
await self.write_file(path, old_text)
|
|
267
|
+
|
|
268
|
+
return ContentResult(
|
|
269
|
+
output=f"Last edit to {path} undone successfully. "
|
|
270
|
+
f"{self._make_output(old_text, str(path))}"
|
|
271
|
+
)
|
|
272
|
+
|
|
273
|
+
async def read_file(self, path: Path) -> str:
|
|
274
|
+
"""Read the content of a file from a given path; raise a ToolError if an error occurs."""
|
|
275
|
+
try:
|
|
276
|
+
import shlex
|
|
277
|
+
|
|
278
|
+
safe_path = shlex.quote(str(path))
|
|
279
|
+
code, out, err = await run(f"cat {safe_path}")
|
|
280
|
+
if code != 0:
|
|
281
|
+
raise ToolError(f"Ran into {err} while trying to read {path}")
|
|
282
|
+
return out
|
|
283
|
+
except Exception as e:
|
|
284
|
+
raise ToolError(f"Ran into {e} while trying to read {path}") from None
|
|
285
|
+
|
|
286
|
+
async def write_file(self, path: Path, file: str) -> None:
|
|
287
|
+
"""Write the content of a file to a given path; raise a ToolError if an error occurs."""
|
|
288
|
+
try:
|
|
289
|
+
import shlex
|
|
290
|
+
|
|
291
|
+
safe_path = shlex.quote(str(path))
|
|
292
|
+
code, _, err = await run(f"cat > {safe_path} << 'EOF'\n{file}\nEOF")
|
|
293
|
+
if code != 0:
|
|
294
|
+
raise ToolError(f"Ran into {err} while trying to write to {path}")
|
|
295
|
+
except Exception as e:
|
|
296
|
+
raise ToolError(f"Ran into {e} while trying to write to {path}") from None
|
|
297
|
+
|
|
298
|
+
def _make_output(
|
|
299
|
+
self,
|
|
300
|
+
file_content: str,
|
|
301
|
+
file_descriptor: str,
|
|
302
|
+
init_line: int = 1,
|
|
303
|
+
expand_tabs: bool = True,
|
|
304
|
+
) -> str:
|
|
305
|
+
"""Generate output for the CLI based on the content of a file."""
|
|
306
|
+
file_content = maybe_truncate(file_content)
|
|
307
|
+
if expand_tabs:
|
|
308
|
+
file_content = file_content.expandtabs()
|
|
309
|
+
file_content = "\n".join(
|
|
310
|
+
[f"{i + init_line:6}\t{line}" for i, line in enumerate(file_content.split("\n"))]
|
|
311
|
+
)
|
|
312
|
+
return (
|
|
313
|
+
f"Here's the result of running `cat -n` on {file_descriptor}:\n" + file_content + "\n"
|
|
314
|
+
)
|