Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(agent-core): edit match tiers, read boundary errors, and watch handover of finished commands

cyh92c882b0aa31
diff --git a/core/agent_core/tools/bash.py b/core/agent_core/tools/bash.py
index fbae71b94..2198ae637 100644
--- a/core/agent_core/tools/bash.py
+++ b/core/agent_core/tools/bash.py
@@ -37,6 +37,7 @@ _MAX_TIMEOUT_S = 2_147_483.647
_PROGRESS_INTERVAL_S = 0.1 # Pi's BASH_UPDATE_THROTTLE_MS
# A job found gone this close to its timeout was killed for it, by this tool or by the job host.
_DEADLINE_SLACK_S = 1.0
+_WATCH_GRACE_S = 0.5
BASH_SCHEMA: Mapping[str, Any] = {
"type": "object",
@@ -188,22 +189,19 @@ class BashTool:
return error_result(f"Could not start the command: {exc}")
output = JobOutput(self._jobs, job_id)
+ # watch=true still lets a command that ends at once report its own result instead of becoming a Watch.
+ handover_at = min(self._window_s, _WATCH_GRACE_S) if watch else self._window_s
handover_error: Optional[Exception] = None
last_progress = ""
while True:
elapsed = time.monotonic() - started
- if handover_error is None and (watch or elapsed >= self._window_s):
- try:
- return handover_result(output, await self._jobs.hand_over(job_id))
- except Exception as exc: # no Watch here: the command stays in the foreground
- logger.info("Job %s stays in the foreground: %s", job_id, exc)
- handover_error = exc
-
- slice_s = _PROGRESS_INTERVAL_S
+ hand_over = handover_error is None and elapsed >= handover_at
+ # A handover is decided only after a fresh status: a command that already ended keeps its own result.
+ slice_s = 0.0 if hand_over else _PROGRESS_INTERVAL_S
if timeout is not None:
slice_s = min(slice_s, max(0.0, timeout - elapsed))
if handover_error is None:
- slice_s = min(slice_s, max(0.0, self._window_s - elapsed))
+ slice_s = min(slice_s, max(0.0, handover_at - elapsed))
status = await self._wait_or_cancel(job_id, slice_s, ctx.cancel)
if status is not None and status.state == "gone" and timeout is not None:
@@ -221,6 +219,13 @@ class BashTool:
if timeout is not None and time.monotonic() - started >= timeout:
await self._jobs.kill(job_id)
return stopped_result(output, _timed_out_line(timeout))
+ if hand_over:
+ try:
+ return handover_result(output, await self._jobs.hand_over(job_id))
+ except Exception as exc: # no Watch here: the command stays in the foreground
+ logger.info("Job %s stays in the foreground: %s", job_id, exc)
+ handover_error = exc
+ continue
if ctx.on_progress is not None and output.poll():
tail = output.snapshot().content
if tail != last_progress:
diff --git a/core/agent_core/tools/edit.py b/core/agent_core/tools/edit.py
index 4c3a26e7f..0d661e4ec 100644
--- a/core/agent_core/tools/edit.py
+++ b/core/agent_core/tools/edit.py
@@ -143,9 +143,9 @@ class EditTool:
arguments = prepare_edit_arguments(arguments)
path = str_arg(arguments, "path")
edits = _edits_arg(arguments)
+ absolute = resolve_to_cwd(path, ctx.cwd)
except ToolInputError as exc:
return error_result(str(exc))
- absolute = resolve_to_cwd(path, ctx.cwd)
async with file_mutation_lock(absolute):
if ctx.cancel.cancelled:
diff --git a/core/agent_core/tools/edit_diff.py b/core/agent_core/tools/edit_diff.py
index 3596ec0a5..2182e9798 100644
--- a/core/agent_core/tools/edit_diff.py
+++ b/core/agent_core/tools/edit_diff.py
@@ -5,7 +5,9 @@ Copyright (c) 2025 Mario Zechner): exact match first, then Pi's deterministic
normalized match with no similarity threshold, every edit matched against the
original, overlapping edits rejected. Avibe adds ``replaceAll`` (from Claude
Code and OpenCode): every occurrence in the tier that matched, each one a span
-for the overlap check.
+for the overlap check. Two Avibe departures from Pi: uniqueness is counted in
+the tier that matched (Pi always counts normalized text), and classic Mac CR
+line endings are restored like CRLF.
"""
from __future__ import annotations
@@ -51,11 +53,11 @@ def split_bom(content: str) -> tuple[str, str]:
def detect_line_ending(content: str) -> str:
- crlf = content.find("\r\n")
- lf = content.find("\n")
- if lf == -1 or crlf == -1:
+ """The style of the first line break. Pi knows CRLF and LF; Avibe also keeps classic Mac CR."""
+ cr, lf = content.find("\r"), content.find("\n")
+ if cr == -1 or (lf != -1 and lf < cr):
return "\n"
- return "\r\n" if crlf < lf else "\n"
+ return "\r\n" if cr + 1 == lf else "\r"
def normalize_to_lf(text: str) -> str:
@@ -63,7 +65,7 @@ def normalize_to_lf(text: str) -> str:
def restore_line_endings(text: str, ending: str) -> str:
- return text.replace("\n", "\r\n") if ending == "\r\n" else text
+ return text if ending == "\n" else text.replace("\n", ending)
def normalize_for_fuzzy_match(text: str) -> str:
@@ -87,16 +89,23 @@ def _find_all(content: str, needle: str) -> list[int]:
return found
-def _find(content: str, old_text: str) -> Optional[tuple[int, int, bool]]:
- """``(index, length, used_fuzzy)`` of the first match, exact before normalized."""
+def _find(content: str, old_text: str) -> Optional[tuple[int, int, int, bool]]:
+ """``(index, length, occurrences, used_fuzzy)`` of the first match, exact before normalized.
+
+ Occurrences are counted in the tier that matched.
+ """
exact = content.find(old_text)
if exact != -1:
- return exact, len(old_text), False
+ return exact, len(old_text), content.count(old_text), False
fuzzy_old = normalize_for_fuzzy_match(old_text)
- fuzzy = normalize_for_fuzzy_match(content).find(fuzzy_old)
+ if not fuzzy_old:
+ # Whitespace that normalizes away would match everywhere, length zero.
+ return None
+ fuzzy_content = normalize_for_fuzzy_match(content)
+ fuzzy = fuzzy_content.find(fuzzy_old)
if fuzzy == -1:
return None
- return fuzzy, len(fuzzy_old), True
+ return fuzzy, len(fuzzy_old), fuzzy_content.count(fuzzy_old), True
def _find_every(content: str, old_text: str) -> list[tuple[int, int]]:
@@ -108,14 +117,6 @@ def _find_every(content: str, old_text: str) -> list[tuple[int, int]]:
return [(index, len(fuzzy_old)) for index in _find_all(normalize_for_fuzzy_match(content), fuzzy_old)]
-def _count_occurrences(content: str, old_text: str) -> int:
- fuzzy_old = normalize_for_fuzzy_match(old_text)
- if not fuzzy_old:
- # Whitespace-only text normalizes to nothing; count it as written.
- return content.count(old_text)
- return normalize_for_fuzzy_match(content).count(fuzzy_old)
-
-
def _not_found(path: str, index: int, total: int) -> EditError:
if total == 1:
return EditError(
@@ -226,7 +227,7 @@ def apply_edits_to_normalized_content(content: str, edits: list[Edit], path: str
if not edit.old_text:
raise _empty(path, index, total)
- used_fuzzy = any(m is not None and m[2] for m in (_find(content, e.old_text) for e in edits))
+ used_fuzzy = any(m is not None and m[3] for m in (_find(content, e.old_text) for e in edits))
base = normalize_for_fuzzy_match(content) if used_fuzzy else content
replacements: list[_Replacement] = []
@@ -240,9 +241,8 @@ def apply_edits_to_normalized_content(content: str, edits: list[Edit], path: str
match = _find(base, edit.old_text)
if match is None:
raise _not_found(path, index, total)
- occurrences = _count_occurrences(base, edit.old_text)
- if occurrences > 1:
- raise _duplicate(path, index, total, occurrences)
+ if match[2] > 1:
+ raise _duplicate(path, index, total, match[2])
replacements.append(_Replacement(index, match[0], match[1], edit.new_text))
replacements.sort(key=lambda r: r.index)
diff --git a/core/agent_core/tools/paths.py b/core/agent_core/tools/paths.py
index e61a67d7a..46eb42c3a 100644
--- a/core/agent_core/tools/paths.py
+++ b/core/agent_core/tools/paths.py
@@ -15,6 +15,8 @@ from contextlib import asynccontextmanager
from typing import AsyncIterator
from urllib.parse import unquote, urlparse
+from core.agent_core.tools.args import ToolInputError
+
_UNICODE_SPACES = re.compile("[\u00a0\u2000-\u200a\u202f\u205f\u3000]")
_NARROW_NO_BREAK_SPACE = "\u202f"
_AM_PM = re.compile(r" (AM|PM)\.", re.IGNORECASE)
@@ -33,7 +35,10 @@ def expand_path(path: str) -> str:
def resolve_to_cwd(path: str, cwd: str) -> str:
+ """The absolute path; raises ``ToolInputError`` for a path no file can have (a NUL byte, possibly from ``%00``)."""
expanded = expand_path(path)
+ if "\x00" in expanded:
+ raise ToolInputError(f"Invalid path: {path!r} contains a NUL byte")
if os.path.isabs(expanded):
return os.path.normpath(expanded)
return os.path.normpath(os.path.join(cwd, expanded))
diff --git a/core/agent_core/tools/read.py b/core/agent_core/tools/read.py
index f471c9840..bf40d0667 100644
--- a/core/agent_core/tools/read.py
+++ b/core/agent_core/tools/read.py
@@ -14,6 +14,7 @@ from __future__ import annotations
import asyncio
import inspect
import os
+import shlex
import struct
from typing import Any, Awaitable, Callable, Mapping, Optional, Union
@@ -38,6 +39,7 @@ ImageSink = Callable[[bytes, str, str], Union[str, Awaitable[str]]]
# resize, so the cap applies to the file as it is.
MAX_INLINE_IMAGE_BYTES = int(4.5 * 1024 * 1024) * 3 // 4
_IMAGE_SNIFF_BYTES = 4100
+_PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
_READ_CHUNK_BYTES = 1024 * 1024
READ_DESCRIPTION = (
@@ -78,13 +80,15 @@ class ReadTool:
except ToolInputError as exc:
return error_result(str(exc))
- absolute = resolve_read_path(path, ctx.cwd)
try:
+ absolute = resolve_read_path(path, ctx.cwd)
mime_type = await asyncio.to_thread(_sniff_image, absolute)
if mime_type is not None:
return await self._read_image(absolute, mime_type)
- # Off the event loop, which every Session and surface shares.
- return await asyncio.to_thread(_read_text, absolute, path, offset, limit)
+ # Off the event loop, which every Session and surface shares; the scan stops on cancel.
+ return await asyncio.to_thread(_read_text, absolute, path, offset, limit, lambda: ctx.cancel.cancelled)
+ except _Aborted:
+ return error_result("Operation aborted")
except OSError as exc:
return error_result(os_error_text(exc))
except ToolInputError as exc:
@@ -120,9 +124,23 @@ class ReadTool:
)
+class _Aborted(Exception):
+ pass
+
+
def _sniff_image(path: str) -> Optional[str]:
+ """The image type to attach, or ``None`` for text. A PNG or JPEG Pi cannot send (animated PNG,
+ JPEG-LS) keeps its family, so it is omitted rather than decoded as text."""
with open(path, "rb") as handle:
- return detect_supported_image_mime_type(handle.read(_IMAGE_SNIFF_BYTES))
+ head = handle.read(_IMAGE_SNIFF_BYTES)
+ supported = detect_supported_image_mime_type(head)
+ if supported is not None:
+ return supported
+ if head.startswith(_PNG_SIGNATURE):
+ return "image/apng" if _is_png(head) else None
+ if head.startswith(b"\xff\xd8\xff"):
+ return "image/jls"
+ return None
def _read_bytes(path: str) -> bytes:
@@ -130,10 +148,12 @@ def _read_bytes(path: str) -> bytes:
return handle.read()
-def _read_text(absolute: str, path: str, offset: Optional[float], limit: Optional[float]) -> ToolResult:
+def _read_text(
+ absolute: str, path: str, offset: Optional[float], limit: Optional[float], cancelled: Callable[[], bool]
+) -> ToolResult:
start_line = max(0, int(offset) - 1) if offset else 0
stop_line = start_line + int(limit) if limit is not None else None
- collected, total_lines, first_line_bytes = _scan_lines(absolute, start_line, stop_line)
+ collected, total_lines, first_line_bytes = _scan_lines(absolute, start_line, stop_line, cancelled)
if start_line >= total_lines:
raise ToolInputError(f"Offset {format_number(offset or 0)} is beyond end of file ({total_lines} lines total)")
@@ -143,7 +163,7 @@ def _read_text(absolute: str, path: str, offset: Optional[float], limit: Optiona
if truncation.first_line_exceeds_limit:
text = (
f"[Line {start_display} is {format_size(first_line_bytes)}, exceeds {format_size(MAX_BYTES)} limit. "
- f"Use bash: sed -n '{start_display}p' {path} | head -c {MAX_BYTES}]"
+ f"Use bash: sed -n '{start_display}p' {shlex.quote(path)} | head -c {MAX_BYTES}]"
)
details["truncation"] = truncation.to_details()
elif truncation.truncated:
@@ -167,7 +187,9 @@ def _read_text(absolute: str, path: str, offset: Optional[float], limit: Optiona
return text_result(text, details=details)
-def _scan_lines(path: str, start: int, stop: Optional[int]) -> tuple[list[str], int, int]:
+def _scan_lines(
+ path: str, start: int, stop: Optional[int], cancelled: Callable[[], bool] = lambda: False
+) -> tuple[list[str], int, int]:
"""Lines ``[start, stop)`` as Pi's ``text.split("\\n")`` gives them, the file's line count, and the
raw size of line ``start``.
@@ -206,6 +228,8 @@ def _scan_lines(path: str, start: int, stop: Optional[int]) -> tuple[list[str],
with open(path, "rb") as handle:
while chunk := handle.read(_READ_CHUNK_BYTES):
+ if cancelled():
+ raise _Aborted
pos = 0
while collecting:
newline = chunk.find(b"\n", pos)
@@ -234,7 +258,7 @@ def detect_supported_image_mime_type(data: bytes) -> Optional[str]:
"""Pi's content sniffing: JPEG, static PNG, GIF, WebP, and BMP."""
if data.startswith(b"\xff\xd8\xff"):
return None if len(data) > 3 and data[3] == 0xF7 else "image/jpeg"
- if data.startswith(b"\x89PNG\r\n\x1a\n"):
+ if data.startswith(_PNG_SIGNATURE):
return "image/png" if _is_png(data) and not _is_animated_png(data) else None
if data.startswith((b"GIF87a", b"GIF89a")):
return "image/gif"
diff --git a/core/agent_core/tools/write.py b/core/agent_core/tools/write.py
index 0602e53d4..a985655b3 100644
--- a/core/agent_core/tools/write.py
+++ b/core/agent_core/tools/write.py
@@ -41,9 +41,9 @@ class WriteTool:
try:
path = str_arg(arguments, "path")
content = str_arg(arguments, "content")
+ absolute = resolve_to_cwd(path, ctx.cwd)
except ToolInputError as exc:
return error_result(str(exc))
- absolute = resolve_to_cwd(path, ctx.cwd)
async with file_mutation_lock(absolute):
# Checked before each step, never in the middle of one, so the lock is held until
# the filesystem operation in progress has finished.
diff --git a/tests/agent_core/tools/test_bash.py b/tests/agent_core/tools/test_bash.py
index a8620b1f8..780ef2005 100644
--- a/tests/agent_core/tools/test_bash.py
+++ b/tests/agent_core/tools/test_bash.py
@@ -67,10 +67,10 @@ async def test_stdin_is_closed(tmp_path, make_ctx):
async def test_timeout_kills_the_tree_including_background_children(tmp_path, make_ctx):
command = f"sleep 30 & echo $! > {tmp_path / 'bg.pid'}; echo started; sleep 30"
- result = await BashTool(_host(tmp_path)).execute({"command": command, "timeout": 0.5}, make_ctx())
+ result = await BashTool(_host(tmp_path)).execute({"command": command, "timeout": 1.5}, make_ctx())
assert result.is_error
- assert result_text(result) == "started\n\n\nCommand timed out after 0.5 seconds"
+ assert result_text(result) == "started\n\n\nCommand timed out after 1.5 seconds"
assert _process_gone(int((tmp_path / "bg.pid").read_text()))
@@ -96,17 +96,18 @@ async def test_abort_kills_the_command(tmp_path, make_ctx):
async def test_the_foreground_window_hands_over_and_the_command_runs_once(tmp_path, make_ctx):
watches = Watches()
host = _host(tmp_path, watches)
- command = f"echo run >> {tmp_path / 'counter'}; echo working; sleep 1; echo finished"
+ command = f"echo run >> {tmp_path / 'counter'}; echo working; sleep 2; echo finished"
- result = await BashTool(host, foreground_window_s=0.3).execute({"command": command}, make_ctx())
+ result = await BashTool(host, foreground_window_s=1.0).execute({"command": command}, make_ctx())
job_id = result.details["job_id"]
path = host.output_path(job_id)
+ text = result_text(result)
assert not result.is_error
- assert result_text(result) == (
+ assert text.startswith(
"Command is still running and is now Watch wch_1. You will get a follow-up message when it finishes.\n\n"
- f"working\n\nFull output: {path}\nCheck: vibe watch show wch_1\nStop: vibe watch remove wch_1"
)
+ assert text.endswith(f"\n\nFull output: {path}\nCheck: vibe watch show wch_1\nStop: vibe watch remove wch_1")
assert (await host.wait(job_id, deadline_s=5)).exit_code == 0
assert open(path).read() == "working\nfinished\n"
assert (tmp_path / "counter").read_text() == "run\n"
@@ -125,8 +126,18 @@ async def test_watch_true_returns_at_once(tmp_path, make_ctx):
await host.kill(result.details["job_id"])
+async def test_watch_true_keeps_the_result_of_a_command_that_already_ended(tmp_path, make_ctx):
+ watches = Watches()
+
+ result = await BashTool(_host(tmp_path, watches)).execute({"command": "exit 3", "watch": True}, make_ctx())
+
+ assert result.is_error
+ assert result_text(result) == "(no output)\n\nCommand exited with code 3"
+ assert watches.by_job == {}
+
+
async def test_without_a_watch_the_command_stays_in_the_foreground(tmp_path, make_ctx):
- result = await BashTool(_host(tmp_path)).execute({"command": "echo hi", "watch": True}, make_ctx())
+ result = await BashTool(_host(tmp_path)).execute({"command": "sleep 1; echo hi", "watch": True}, make_ctx())
assert not result.is_error
assert result_text(result) == (
@@ -157,7 +168,7 @@ async def test_settlement_reports_each_job_state(tmp_path, make_ctx):
async def test_a_timeout_holds_across_handover_and_a_restart(tmp_path, make_ctx):
"""J3: the deadline is the job's, so the next owner enforces it."""
result = await BashTool(_host(tmp_path, Watches())).execute(
- {"command": "echo begun; sleep 30", "timeout": 0.5, "watch": True}, make_ctx()
+ {"command": "echo begun; sleep 30", "timeout": 1.5, "watch": True}, make_ctx()
)
job_id = result.details["job_id"]
assert result_text(result).startswith("Command is still running")
@@ -168,5 +179,5 @@ async def test_a_timeout_holds_across_handover_and_a_restart(tmp_path, make_ctx)
assert status.state == "gone"
assert restarted.stop_reason(job_id) == "timeout"
settled = await settle_bash_call(restarted, "ses_test", "toolu_1")
- assert result_text(settled) == "begun\n\n\nCommand timed out after 0.5 seconds"
+ assert result_text(settled) == "begun\n\n\nCommand timed out after 1.5 seconds"
assert not os.path.exists(os.path.join(restarted.job_dir(job_id), "exit"))
diff --git a/tests/agent_core/tools/test_read.py b/tests/agent_core/tools/test_read.py
index 009dc977f..98f33b432 100644
--- a/tests/agent_core/tools/test_read.py
+++ b/tests/agent_core/tools/test_read.py
@@ -9,6 +9,7 @@ import zlib
import pytest
import core.agent_core.tools.read as read_module
+from core.agent_core.cancel import CancelToken
from core.agent_core.messages import ImageBlock, TextBlock
from core.agent_core.tools.read import ReadTool
from core.agent_core.tools.truncate import truncate_head
@@ -58,11 +59,34 @@ async def test_offset_beyond_the_end_is_an_error(tmp_path, make_ctx):
async def test_an_over_long_first_line_points_at_bash(tmp_path, make_ctx):
- (tmp_path / "big.txt").write_text("short\n" + "x" * 61_440 + "\nafter\n")
+ (tmp_path / "big file.txt").write_text("short\n" + "x" * 61_440 + "\nafter\n")
- text = result_text(await _read(make_ctx, path="big.txt", offset=2))
+ text = result_text(await _read(make_ctx, path="big file.txt", offset=2))
- assert text == "[Line 2 is 60.0KB, exceeds 50.0KB limit. Use bash: sed -n '2p' big.txt | head -c 51200]"
+ assert text == "[Line 2 is 60.0KB, exceeds 50.0KB limit. Use bash: sed -n '2p' 'big file.txt' | head -c 51200]"
+
+
+class _CancelledAfter(CancelToken):
+ """A cancel that lands after the scan has read a few chunks."""
+
+ def __init__(self, reads: int) -> None:
+ super().__init__()
+ self._reads_left = reads
+
+ @property
+ def cancelled(self) -> bool:
+ self._reads_left -= 1
+ return self._reads_left < 0
+
+
+async def test_cancel_stops_a_long_scan(tmp_path, make_ctx, monkeypatch):
+ monkeypatch.setattr(read_module, "_READ_CHUNK_BYTES", 1024)
+ (tmp_path / "long.txt").write_bytes(b"x\n" * 500_000)
+
+ result = await ReadTool().execute({"path": "long.txt"}, make_ctx(cancel=_CancelledAfter(reads=10)))
+
+ assert result.is_error
+ assert result_text(result) == "Operation aborted"
def _whole_file_read(data: bytes, start: int, stop):
@@ -102,14 +126,15 @@ async def test_streaming_matches_reading_the_whole_file(tmp_path, monkeypatch):
assert first_line_bytes == len(data.split(b"\n")[start])
-def _png() -> bytes:
- def chunk(kind: bytes, body: bytes) -> bytes:
- return struct.pack(">I", len(body)) + kind + body + struct.pack(">I", zlib.crc32(kind + body))
+def _chunk(kind: bytes, body: bytes) -> bytes:
+ return struct.pack(">I", len(body)) + kind + body + struct.pack(">I", zlib.crc32(kind + body))
- ihdr = struct.pack(">IIBBBBB", 1, 1, 8, 2, 0, 0, 0)
- return (
- b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IDAT", zlib.compress(b"\0\xff\0\0")) + chunk(b"IEND", b"")
- )
+
+def _png(*, animated: bool = False) -> bytes:
+ ihdr = _chunk(b"IHDR", struct.pack(">IIBBBBB", 1, 1, 8, 2, 0, 0, 0))
+ actl = _chunk(b"acTL", struct.pack(">II", 1, 0)) if animated else b""
+ idat = _chunk(b"IDAT", zlib.compress(b"\0\xff\0\0"))
+ return b"\x89PNG\r\n\x1a\n" + ihdr + actl + idat + _chunk(b"IEND", b"")
async def test_an_image_is_stored_through_the_sink_and_attached(tmp_path, make_ctx):
@@ -138,6 +163,13 @@ async def test_an_image_is_stored_through_the_sink_and_attached(tmp_path, make_c
None,
"Read image file [image/bmp]\n[Image omitted: could not be converted to a supported inline image format.]",
),
+ (
+ # Recognized but not sendable as it is: omitted, never decoded as text.
+ "anim.png",
+ _png(animated=True),
+ None,
+ "Read image file [image/apng]\n[Image omitted: could not be converted to a supported inline image format.]",
+ ),
(
"pic.png",
_png(),
diff --git a/tests/agent_core/tools/test_write_edit.py b/tests/agent_core/tools/test_write_edit.py
index cdf37d2b9..a9d2352f7 100644
--- a/tests/agent_core/tools/test_write_edit.py
+++ b/tests/agent_core/tools/test_write_edit.py
@@ -5,6 +5,7 @@ from __future__ import annotations
import pytest
from core.agent_core.tools.edit import EditTool
+from core.agent_core.tools.read import ReadTool
from core.agent_core.tools.write import WriteTool
from tests.agent_core.tools.conftest import result_text
@@ -58,13 +59,23 @@ async def test_replace_all_replaces_every_occurrence(tmp_path, make_ctx):
assert (tmp_path / "f.txt").read_text() == "baz(1)\nqux\nbaz(2)\nbaz(3)\n"
-async def test_bom_and_crlf_are_preserved(tmp_path, make_ctx):
- (tmp_path / "win.txt").write_bytes("\ufeffone\r\ntwo\r\nthree\r\n".encode())
[email protected]("ending", ["\r\n", "\r"])
+async def test_bom_and_line_endings_are_preserved(tmp_path, make_ctx, ending):
+ (tmp_path / "f.txt").write_bytes(f"\ufeffone{ending}two{ending}three{ending}".encode())
- result = await _edit(make_ctx, "win.txt", {"oldText": "two\nthree", "newText": "2\n3"})
+ result = await _edit(make_ctx, "f.txt", {"oldText": "two\nthree", "newText": "2\n3"})
assert not result.is_error, result_text(result)
- assert (tmp_path / "win.txt").read_bytes() == "\ufeffone\r\n2\r\n3\r\n".encode()
+ assert (tmp_path / "f.txt").read_bytes() == f"\ufeffone{ending}2{ending}3{ending}".encode()
+
+
+async def test_an_exact_match_is_unique_even_with_a_normalized_twin(tmp_path, make_ctx):
+ (tmp_path / "f.txt").write_text('say "Hi"\nsay \u201cHi\u201d\n')
+
+ result = await _edit(make_ctx, "f.txt", {"oldText": 'say "Hi"', "newText": 'say "Hello"'})
+
+ assert not result.is_error, result_text(result)
+ assert (tmp_path / "f.txt").read_text() == 'say "Hello"\nsay \u201cHi\u201d\n'
@pytest.mark.parametrize(
@@ -75,6 +86,12 @@ async def test_bom_and_crlf_are_preserved(tmp_path, make_ctx):
"Could not find the exact text in f.txt. The old text must match exactly including all whitespace and "
"newlines.",
),
+ (
+ # Absent whitespace normalizes to nothing, which must not match everywhere.
+ [{"oldText": "\t", "newText": "x"}],
+ "Could not find the exact text in f.txt. The old text must match exactly including all whitespace and "
+ "newlines.",
+ ),
(
[{"oldText": "alpha", "newText": "A"}, {"oldText": "missing", "newText": "x"}],
"Could not find edits[1] in f.txt. The oldText must match exactly including all whitespace and newlines.",
@@ -113,3 +130,18 @@ async def test_a_failing_edit_writes_nothing(tmp_path, make_ctx, edits, message)
assert result.is_error
assert result_text(result) == message
assert (tmp_path / "f.txt").read_text() == original
+
+
+ ("tool", "arguments"),
+ [
+ (ReadTool(), {"path": "a\x00b"}),
+ (WriteTool(), {"path": "a\x00b", "content": "x"}),
+ (EditTool(), {"path": "file:///tmp/a%00b", "edits": [{"oldText": "a", "newText": "b"}]}),
+ ],
+)
+async def test_a_path_no_file_can_have_is_an_error_result(make_ctx, tool, arguments):
+ result = await tool.execute(arguments, make_ctx())
+
+ assert result.is_error
+ assert result_text(result) == f"Invalid path: {arguments['path']!r} contains a NUL byte"