coreloop 0.1.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.
@@ -0,0 +1,188 @@
1
+ """Tool registration via the ``@tool`` decorator."""
2
+
3
+ import inspect
4
+ import types
5
+ import typing
6
+ import warnings
7
+ from dataclasses import dataclass
8
+ from typing import Any, Callable, Coroutine, overload
9
+
10
+
11
+ @dataclass
12
+ class ToolInfo:
13
+ """Metadata describing a registered tool."""
14
+
15
+ name: str
16
+ description: str
17
+ parameters: dict[str, Any] # JSON Schema
18
+ fn: Callable[..., Coroutine[Any, Any, str]]
19
+ """The async callable that executes this tool."""
20
+
21
+ def __call__(self, *args: Any, **kwargs: Any) -> Coroutine[Any, Any, str]:
22
+ """Invoke the wrapped tool function.
23
+
24
+ ``@tool`` returns the ``ToolInfo``, so making it callable keeps the
25
+ decorated name usable directly -- ``await my_tool(...)`` delegates to
26
+ the underlying function.
27
+ """
28
+ return self.fn(*args, **kwargs)
29
+
30
+
31
+ # Global registry: tool name -> ToolInfo
32
+ _TOOL_REGISTRY: dict[str, ToolInfo] = {}
33
+
34
+
35
+ def _infer_parameters(fn: Callable) -> dict[str, Any]:
36
+ """Build a JSON Schema for *fn* from its type annotations."""
37
+ sig = inspect.signature(fn)
38
+ hints = {k: v for k, v in (getattr(fn, "__annotations__", {}) or {}).items() if k != "return"}
39
+
40
+ properties: dict[str, dict[str, Any]] = {}
41
+ required: list[str] = []
42
+
43
+ for name, param in sig.parameters.items():
44
+ if name == "return":
45
+ continue
46
+ if param.kind in (param.VAR_POSITIONAL, param.VAR_KEYWORD):
47
+ continue # *args, **kwargs not supported yet
48
+ if param.default is inspect.Parameter.empty:
49
+ required.append(name)
50
+ type_hint = hints.get(name)
51
+ js_type = _pytype_to_jsonschema(type_hint) if type_hint else {}
52
+ prop: dict[str, Any] = js_type.copy()
53
+ if param.default is not inspect.Parameter.empty:
54
+ prop["default"] = param.default
55
+ properties[name] = prop
56
+
57
+ return {
58
+ "type": "object",
59
+ "properties": properties,
60
+ "required": required,
61
+ }
62
+
63
+
64
+ def _pytype_to_jsonschema(tp: type) -> dict[str, Any]:
65
+ """Best-effort Python type -> JSON Schema type mapping."""
66
+ origin = typing.get_origin(tp)
67
+ args = typing.get_args(tp) if origin else ()
68
+
69
+ # Union types like int | None (types.UnionType) or Optional[int] (typing.Union)
70
+ if origin is types.UnionType or origin is typing.Union:
71
+ non_none = [a for a in args if a is not type(None)]
72
+ if len(non_none) == 1:
73
+ # Optional[X] -> use the schema for X, allow null via default
74
+ return _pytype_to_jsonschema(non_none[0])
75
+ # Mixed union -- fall through to generic string
76
+ return {"type": "string"}
77
+
78
+ if origin is typing.Literal:
79
+ # All Literal values must be the same JSON type for a clean enum
80
+ values = list(args)
81
+ if all(isinstance(v, str) for v in values):
82
+ return {"type": "string", "enum": values}
83
+ if all(isinstance(v, int) for v in values):
84
+ return {"type": "integer", "enum": values}
85
+ return {"enum": values}
86
+ if origin is list:
87
+ item_tp = args[0] if args else str
88
+ return {"type": "array", "items": _pytype_to_jsonschema(item_tp)}
89
+ if origin is dict:
90
+ return {"type": "object"}
91
+ if origin is str or tp is str:
92
+ return {"type": "string"}
93
+ if origin is int or tp is int:
94
+ return {"type": "integer"}
95
+ if origin is float or tp is float:
96
+ return {"type": "number"}
97
+ if origin is bool or tp is bool:
98
+ return {"type": "boolean"}
99
+ warnings.warn(
100
+ f"_pytype_to_jsonschema: unrecognised type {tp!r}, falling back to string. "
101
+ "Consider using str, int, float, bool, list[...], dict, or Optional[...] instead.",
102
+ stacklevel=3,
103
+ )
104
+ return {"type": "string"}
105
+
106
+
107
+ @overload
108
+ def tool(
109
+ fn: Callable[..., Coroutine[Any, Any, str]],
110
+ *,
111
+ name: str | None = None,
112
+ description: str | None = None,
113
+ allow_override: bool = False,
114
+ ) -> ToolInfo:
115
+ """Use as @tool directly on a function."""
116
+ ...
117
+
118
+
119
+ @overload
120
+ def tool(
121
+ *,
122
+ name: str | None = None,
123
+ description: str | None = None,
124
+ allow_override: bool = False,
125
+ ) -> Callable[[Callable[..., Coroutine[Any, Any, str]]], ToolInfo]:
126
+ """Use as @tool(...) with keyword arguments."""
127
+ ...
128
+
129
+
130
+ def tool(
131
+ fn: Callable[..., Coroutine[Any, Any, str]] | None = None,
132
+ *,
133
+ name: str | None = None,
134
+ description: str | None = None,
135
+ allow_override: bool = False,
136
+ ) -> ToolInfo | Callable[[Callable[..., Coroutine[Any, Any, str]]], ToolInfo]:
137
+ """Decorator to register an async function as a tool.
138
+
139
+ Usage::
140
+
141
+ @tool
142
+ async def read(path: str) -> str:
143
+ ...
144
+
145
+ @tool(name="my_read", description="Read a file")
146
+ async def my_read(path: str) -> str:
147
+ ...
148
+
149
+ Raises ``ValueError`` if a tool with the same name is already registered,
150
+ unless ``allow_override=True`` is passed.
151
+ """
152
+
153
+ def register(f: Callable[..., Coroutine[Any, Any, str]]) -> ToolInfo:
154
+ """Build and register a ToolInfo for the decorated function."""
155
+ tool_name = name or getattr(f, "__name__", "")
156
+ if tool_name in _TOOL_REGISTRY and not allow_override:
157
+ raise ValueError(
158
+ f"Tool {tool_name!r} is already registered. "
159
+ "Use a different name or pass allow_override=True."
160
+ )
161
+ tool_desc = description or (f.__doc__ and f.__doc__.strip()) or ""
162
+ info = ToolInfo(
163
+ name=tool_name,
164
+ description=tool_desc,
165
+ parameters=_infer_parameters(f),
166
+ fn=f,
167
+ )
168
+ _TOOL_REGISTRY[tool_name] = info
169
+ return info
170
+
171
+ if fn is not None:
172
+ return register(fn)
173
+ return register
174
+
175
+
176
+ def clear_registry() -> None:
177
+ """Remove all registered tools. Primarily for use in tests."""
178
+ _TOOL_REGISTRY.clear()
179
+
180
+
181
+ def get_tool(name: str) -> ToolInfo | None:
182
+ """Lookup a tool by name."""
183
+ return _TOOL_REGISTRY.get(name)
184
+
185
+
186
+ def list_tools() -> list[ToolInfo]:
187
+ """Return all registered tools."""
188
+ return list(_TOOL_REGISTRY.values())
@@ -0,0 +1,31 @@
1
+ import os
2
+ from pathlib import Path
3
+
4
+ from ..tool_registry import ToolInfo
5
+ from .edit import make_edit_tool
6
+ from .ls import make_ls_tool
7
+ from .read import make_read_tool
8
+ from .grep import make_grep_tool
9
+
10
+
11
+ def make_tools(
12
+ allowed_root: str | Path | None = None,
13
+ *,
14
+ read_max_lines: int = 100,
15
+ read_max_bytes: int = 10 * 1024 * 1024,
16
+ ls_max_entries: int = 500,
17
+ edit_max_bytes: int = 10 * 1024 * 1024,
18
+ search_max_chars: int = 20_000,
19
+ search_timeout: float = 30.0,
20
+ ) -> list[ToolInfo]:
21
+ """Build the built-in file tools scoped to *allowed_root*.
22
+
23
+ If *allowed_root* is ``None`` the current working directory is used.
24
+ """
25
+ root = str(Path(allowed_root or os.getcwd()).resolve(strict=True))
26
+ return [
27
+ make_read_tool(root, max_lines=read_max_lines, max_bytes=read_max_bytes),
28
+ make_ls_tool(root, max_entries=ls_max_entries),
29
+ make_edit_tool(root, max_bytes=edit_max_bytes),
30
+ make_grep_tool(root, max_chars=search_max_chars, search_timeout=search_timeout),
31
+ ]
@@ -0,0 +1,59 @@
1
+ """Shared helpers for built-in file tools: path resolution and ToolInfo construction."""
2
+
3
+ import os
4
+ from pathlib import Path
5
+
6
+ from ..tool_registry import ToolInfo, _infer_parameters
7
+
8
+ _MAX_READ_BYTES = 10 * 1024 * 1024 # 10 MB
9
+
10
+
11
+ def _resolve_safe(requested: str, root: "Path | str") -> str:
12
+ """Resolve *requested* relative to *root* and raise ValueError on path traversal."""
13
+ if not isinstance(requested, str):
14
+ raise ValueError(f"path must be a string, got {type(requested).__name__}")
15
+
16
+ raw = Path(requested)
17
+ root_path = Path(root)
18
+ if not raw.is_absolute():
19
+ raw = root_path / raw
20
+
21
+ try:
22
+ resolved = raw.resolve(strict=False)
23
+ except OSError as exc:
24
+ raise ValueError(f"cannot resolve path {requested!r}: {exc}") from exc
25
+
26
+ try:
27
+ resolved.relative_to(root_path)
28
+ except ValueError:
29
+ raise ValueError(
30
+ f"path traversal denied: {requested!r} resolves outside allowed root {root_path}"
31
+ ) from None
32
+
33
+ return str(resolved)
34
+
35
+
36
+ def _resolve_safe_strict(requested: str, root: "Path | str") -> str:
37
+ """Like _resolve_safe, but also raises ValueError if the resolved path does not exist."""
38
+ resolved = _resolve_safe(requested, root)
39
+ if not os.path.exists(resolved):
40
+ raise ValueError(f"path does not exist: {requested!r}")
41
+ return resolved
42
+
43
+
44
+ def _fmt_size(size: float) -> str:
45
+ """Format *size* in bytes as a human-readable string (B, KB, MB, GB, TB)."""
46
+ for unit in ("B", "KB", "MB", "GB"):
47
+ if size < 1024:
48
+ return f"{size:.0f} {unit}" if unit == "B" else f"{size:.1f} {unit}"
49
+ size /= 1024
50
+ return f"{size:.1f} TB"
51
+
52
+
53
+ def _make_tool_info(fn, **overrides) -> ToolInfo:
54
+ """Build a ToolInfo from a function, inferring name, description, and schema."""
55
+ name = overrides.pop("name", fn.__name__)
56
+ desc = overrides.pop("description", (fn.__doc__ or "").strip())
57
+ params = _infer_parameters(fn)
58
+ params.update(overrides.pop("parameters", {}))
59
+ return ToolInfo(name=name, description=desc, parameters=params, fn=fn)
coreloop/tools/bash.py ADDED
@@ -0,0 +1,252 @@
1
+ """bash.py -- run shell commands via bash with best-effort guardrails.
2
+
3
+ Uses ``asyncio.create_subprocess_exec`` (matching ``grep.py``'s pattern)
4
+ with ``bash -c`` for portable command execution.
5
+
6
+ This is NOT a sandbox. Commands run with the host user's full privileges and can
7
+ read, write, or delete anything that account can reach, and make network calls.
8
+ The guardrails below reduce obvious accidents; they are not a security boundary.
9
+
10
+ Guardrails:
11
+
12
+ * A small blocklist rejects a few catastrophic patterns (``rm -rf /``, ``mkfs``,
13
+ fork bombs, ...). Trivial variants intentionally slip through -- treat it as a
14
+ speed bump, not a fence.
15
+ * The working directory is validated to stay inside the allowed root (this does
16
+ NOT confine the command itself -- only its initial ``cwd``).
17
+ * Output is middle-truncated at a configurable char limit.
18
+ * Timeout kills the entire process group (Unix) or the process (Windows).
19
+ """
20
+
21
+ import asyncio
22
+ import os
23
+ import re
24
+ import signal
25
+ import sys
26
+ from pathlib import Path
27
+
28
+ from ..tool_registry import ToolInfo
29
+ from ._shared import _make_tool_info, _resolve_safe_strict
30
+
31
+ DEFAULT_DANGEROUS_PATTERNS: list[str] = [
32
+ # rm -rf (any flag order/combo containing r or f) targeting the filesystem
33
+ # root or a top-level dir: /, /etc, /home, /tmp/ ... Deliberately does NOT
34
+ # match deeper paths like /tmp/build so ordinary recursive deletes still work.
35
+ r"\brm\s+-\w*[rf]\w*\s+/\w*/?(?:\s|$)",
36
+ r"\bdd\s+if=",
37
+ r">\s*/dev/sd",
38
+ r":\(\)\s*\{",
39
+ r"\bmkfs\.",
40
+ r"\bmkswap\b",
41
+ r"chmod\s+777\s+/",
42
+ r">\s*/dev/sda",
43
+ ]
44
+
45
+
46
+ def make_bash_tool(
47
+ root: str,
48
+ *,
49
+ max_chars: int = 10_000,
50
+ max_raw_bytes: int = 100 * 1024,
51
+ default_timeout: int = 180,
52
+ max_timeout: int = 300,
53
+ dangerous_patterns: list[str] | None = None,
54
+ ) -> ToolInfo:
55
+ """Build a ``bash`` tool scoped to *root*.
56
+
57
+ Parameters
58
+ ----------
59
+ root :
60
+ Absolute path to the allowed root directory. All commands and
61
+ working-directory values are validated against this.
62
+ max_chars :
63
+ Output character cap before middle-truncation kicks in.
64
+ """
65
+ root_path = Path(root).resolve()
66
+ _patterns = [
67
+ re.compile(p)
68
+ for p in (
69
+ dangerous_patterns if dangerous_patterns is not None else DEFAULT_DANGEROUS_PATTERNS
70
+ )
71
+ ]
72
+
73
+ async def bash(
74
+ command: str,
75
+ timeout: int | None = default_timeout,
76
+ workdir: str | None = None,
77
+ ) -> str:
78
+ """Execute a shell command via bash and return combined stdout+stderr.
79
+
80
+ Safety features:
81
+
82
+ - Dangerous command patterns are blocked with a clear error.
83
+ - Working directory is validated to stay inside the allowed root.
84
+ - Output is capped at 10,000 chars with middle truncation
85
+ (preserves first 40% and last 40%, removes the middle).
86
+
87
+ Parameters
88
+ ----------
89
+ command :
90
+ Shell command to execute via ``bash -c``.
91
+ timeout :
92
+ Max seconds to wait for completion (default 180, max 300).
93
+ The outer agent-level ``tool_timeout`` also applies as an
94
+ additional safety net.
95
+ workdir :
96
+ Working directory for the command. Defaults to the project
97
+ root. Must resolve within the allowed root.
98
+ """
99
+ # --- dangerous command guard ---
100
+ for pattern in _patterns:
101
+ if pattern.search(command):
102
+ return f"Error: command matches blocked pattern ({pattern.pattern!r})"
103
+
104
+ # --- resolve working directory ---
105
+ cwd = str(root_path)
106
+ if workdir is not None:
107
+ try:
108
+ cwd = _resolve_safe_strict(workdir, root_path)
109
+ except ValueError as exc:
110
+ return f"Error: {exc}"
111
+
112
+ # --- clamp timeout ---
113
+ _timeout = min(int(timeout or default_timeout), max_timeout)
114
+
115
+ # --- resolve bash executable ---
116
+ executable = _resolve_bash()
117
+ if executable is None:
118
+ return _bash_not_found_hint()
119
+
120
+ # --- spawn subprocess ---
121
+ try:
122
+ proc = await asyncio.create_subprocess_exec(
123
+ executable,
124
+ "-c",
125
+ command,
126
+ stdout=asyncio.subprocess.PIPE,
127
+ stderr=asyncio.subprocess.STDOUT,
128
+ cwd=cwd,
129
+ preexec_fn=_preexec_setpgid if sys.platform != "win32" else None,
130
+ )
131
+ try:
132
+ stdout, _ = await asyncio.wait_for(proc.communicate(), timeout=_timeout)
133
+ except asyncio.TimeoutError:
134
+ _kill_process_group(proc)
135
+ await proc.communicate()
136
+ return (
137
+ f"Error: command timed out after {_timeout}s. "
138
+ "Try increasing timeout or simplifying the command."
139
+ )
140
+ except FileNotFoundError:
141
+ return "Error: bash not found on PATH"
142
+ except OSError as exc:
143
+ return f"Error: {exc}"
144
+
145
+ # --- decode with raw byte cap ---
146
+ raw = stdout[:max_raw_bytes]
147
+ truncated_wire = len(stdout) > max_raw_bytes
148
+ output = raw.decode("utf-8", errors="replace")
149
+
150
+ # --- middle truncation ---
151
+ if truncated_wire or len(output) > max_chars:
152
+ total = len(stdout)
153
+ head_len = max_chars * 4 // 10
154
+ tail_len = max_chars * 4 // 10
155
+ head = output[:head_len]
156
+ tail = output[-tail_len:] if tail_len > 0 else ""
157
+ output = (
158
+ f"{head}\n"
159
+ f"[Truncated: first {head_len} and last {tail_len} "
160
+ f"chars of {total} total chars shown. "
161
+ f"Simplify the command or write output to a file.]\n"
162
+ f"{tail}"
163
+ )
164
+
165
+ # --- prepend exit code on failure ---
166
+ exit_code = proc.returncode
167
+ if exit_code != 0:
168
+ output = f"Exit code: {exit_code}\n{output}"
169
+
170
+ return output.rstrip("\n")
171
+
172
+ return _make_tool_info(bash)
173
+
174
+
175
+ # ---------------------------------------------------------------------------
176
+ # Internal helpers
177
+ # ---------------------------------------------------------------------------
178
+
179
+
180
+ def _preexec_setpgid() -> None:
181
+ """Create a new process group so we can kill the whole tree on timeout.
182
+
183
+ Used as ``preexec_fn`` argument to ``create_subprocess_exec`` on Unix.
184
+ No-op on Windows (``None`` is passed instead).
185
+ """
186
+ setpgrp = getattr(os, "setpgrp", None)
187
+ if setpgrp is not None:
188
+ setpgrp()
189
+
190
+
191
+ def _kill_process_group(proc: asyncio.subprocess.Process) -> None:
192
+ """Terminate the process group, falling back to SIGKILL after 2 s.
193
+
194
+ On Windows falls back to ``proc.kill()`` immediately.
195
+ """
196
+ if sys.platform == "win32":
197
+ proc.kill()
198
+ return
199
+
200
+ try:
201
+ pgid = os.getpgid(proc.pid)
202
+ os.killpg(pgid, signal.SIGTERM)
203
+ except ProcessLookupError, PermissionError, OSError:
204
+ proc.kill()
205
+ return
206
+
207
+ # --- async-safe SIGKILL timer ---
208
+ def _force_kill() -> None:
209
+ try:
210
+ os.killpg(pgid, signal.SIGKILL)
211
+ except ProcessLookupError, OSError:
212
+ pass
213
+
214
+ import threading
215
+
216
+ threading.Timer(2.0, _force_kill).start()
217
+
218
+
219
+ def _resolve_bash() -> str | None:
220
+ """Return the path to a usable ``bash`` executable, or ``None``."""
221
+ # 1. Try PATH first
222
+ import shutil
223
+
224
+ exe = shutil.which("bash")
225
+ if exe:
226
+ return exe
227
+
228
+ # 2. On Windows, probe common Git for Windows install paths
229
+ if sys.platform == "win32":
230
+ candidates = [
231
+ r"C:\Program Files\Git\bin\bash.exe",
232
+ r"C:\Program Files (x86)\Git\bin\bash.exe",
233
+ str(Path.home() / "AppData" / "Local" / "Programs" / "Git" / "bin" / "bash.exe"),
234
+ ]
235
+ for candidate in candidates:
236
+ if Path(candidate).exists():
237
+ return candidate
238
+
239
+ return None
240
+
241
+
242
+ def _bash_not_found_hint() -> str:
243
+ """Return a user-friendly error message when bash cannot be found."""
244
+ if sys.platform == "win32":
245
+ return (
246
+ "Error: bash not found. "
247
+ "Install Git for Windows (winget install Git.Git) or "
248
+ "ensure bash.exe is on PATH."
249
+ )
250
+ return (
251
+ "Error: bash not found on PATH. Install bash (apt install bash, brew install bash, etc.)."
252
+ )
coreloop/tools/edit.py ADDED
@@ -0,0 +1,154 @@
1
+ """edit.py -- atomic string-replace edit tool for text files."""
2
+
3
+ import os
4
+ import tempfile
5
+ from pathlib import Path
6
+
7
+ from ..tool_registry import ToolInfo
8
+ from ._shared import _fmt_size, _make_tool_info, _resolve_safe, _resolve_safe_strict
9
+
10
+
11
+ def _character_line(content: str, pos: int) -> int:
12
+ """Return the 1-based line number for character position *pos* in *content*."""
13
+ return content[:pos].count("\n") + 1
14
+
15
+
16
+ def _find_occurrence_near_line(content: str, old_text: str, target_line: int) -> int:
17
+ """Find the first occurrence of *old_text* whose 1-based line number
18
+ matches *target_line*. Returns the character index or ``-1``."""
19
+ idx = -1
20
+ while True:
21
+ idx = content.find(old_text, idx + 1)
22
+ if idx < 0:
23
+ break
24
+ if _character_line(content, idx) == target_line:
25
+ return idx
26
+ return -1
27
+
28
+
29
+ def make_edit_tool(root: str, *, max_bytes: int = 10 * 1024 * 1024) -> ToolInfo:
30
+ """Build an edit tool scoped to *root* with an atomic write via a temp file."""
31
+ root_path = Path(root).resolve()
32
+
33
+ async def edit(
34
+ path: str,
35
+ old_text: str,
36
+ new_text: str,
37
+ line_hint: int | None = None,
38
+ ) -> str:
39
+ """Use this to make a targeted edit to a file by replacing an exact string. To create a new file, pass old_text as an empty string.
40
+
41
+ If *old_text* appears multiple times, ``line_hint`` is required to
42
+ disambiguate. Pass the 1-based line number where the text to
43
+ replace appears.
44
+
45
+ To create a new file, pass ``old_text=""`` - the file must not already
46
+ exist. Parent directories are created automatically.
47
+
48
+ Parameters
49
+ ----------
50
+ path :
51
+ Relative or absolute path to the file.
52
+ old_text :
53
+ Exact text to search for (must appear exactly once, unless
54
+ ``line_hint`` is given). Pass ``""`` to create a new file.
55
+ new_text :
56
+ Replacement text (or full content when creating a new file).
57
+ line_hint :
58
+ Optional 1-based line number that *old_text* appears on.
59
+ Required when *old_text* appears more than once.
60
+ """
61
+ if not old_text:
62
+ try:
63
+ safe = _resolve_safe(path, root_path)
64
+ except ValueError as exc:
65
+ return f"Error: {exc}"
66
+ if not Path(safe).exists():
67
+ try:
68
+ Path(safe).parent.mkdir(parents=True, exist_ok=True)
69
+ with tempfile.NamedTemporaryFile(
70
+ "w", dir=Path(safe).parent, delete=False, encoding="utf-8", suffix=".tmp"
71
+ ) as tmp:
72
+ tmp.write(new_text)
73
+ tmp_path = tmp.name
74
+ os.replace(tmp_path, safe)
75
+ except OSError as exc:
76
+ return f"Error: cannot create {path!r}: {exc}"
77
+ return f"Created {path!r}"
78
+ # file exists and old_text is empty -- fall through to the empty-file check below
79
+ else:
80
+ try:
81
+ safe = _resolve_safe_strict(path, root_path)
82
+ except ValueError as exc:
83
+ return f"Error: {exc}"
84
+
85
+ try:
86
+ file_size = Path(safe).stat().st_size
87
+ except OSError as exc:
88
+ return f"Error: cannot stat {path!r}: {exc}"
89
+
90
+ if file_size > max_bytes:
91
+ return (
92
+ f"Error: {path!r} is too large to edit "
93
+ f"({_fmt_size(file_size)} > {_fmt_size(max_bytes)})"
94
+ )
95
+
96
+ try:
97
+ with open(safe, encoding="utf-8", errors="strict") as f:
98
+ content = f.read()
99
+ except UnicodeDecodeError:
100
+ return f"Error: {path!r} contains non-UTF-8 bytes; cannot edit"
101
+ except OSError as exc:
102
+ return f"Error: cannot read {path!r}: {exc}"
103
+
104
+ if not old_text:
105
+ if content:
106
+ return (
107
+ f"Error: {path!r} already has content. "
108
+ "Pass old_text with the exact text to replace. "
109
+ "Empty old_text only works for creating new files."
110
+ )
111
+ idx = 0
112
+ else:
113
+ if old_text not in content:
114
+ return f"Error: old_text not found in {path!r}"
115
+
116
+ count = content.count(old_text)
117
+
118
+ if count == 1:
119
+ idx = content.find(old_text)
120
+ elif line_hint is not None:
121
+ idx = _find_occurrence_near_line(content, old_text, line_hint)
122
+ if idx < 0:
123
+ return (
124
+ f"Error: old_text {old_text!r} appears {count} times in "
125
+ f"{path!r} but none are on line {line_hint}"
126
+ )
127
+ else:
128
+ return (
129
+ f"Error: old_text {old_text!r} appears {count} times in "
130
+ f"{path!r}. Provide line_hint to specify which occurrence "
131
+ f"to replace."
132
+ )
133
+
134
+ new_content = content[:idx] + new_text + content[idx + len(old_text) :]
135
+
136
+ tmp_path = None
137
+ try:
138
+ with tempfile.NamedTemporaryFile(
139
+ "w", dir=Path(safe).parent, delete=False, encoding="utf-8", suffix=".tmp"
140
+ ) as tmp:
141
+ tmp.write(new_content)
142
+ tmp_path = tmp.name
143
+ os.replace(tmp_path, safe)
144
+ except OSError as exc:
145
+ if tmp_path is not None:
146
+ try:
147
+ os.unlink(tmp_path)
148
+ except OSError:
149
+ pass
150
+ return f"Error: cannot write {path!r}: {exc}"
151
+
152
+ return f"Replaced 1 occurrence in {path!r}"
153
+
154
+ return _make_tool_info(edit)