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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(agent-core): every file kind and failure point has a defined result
cyh48de47b67a37
diff --git a/core/agent_core/tools/args.py b/core/agent_core/tools/args.pyindex 44ebe0e7a..656db36bd 100644--- a/core/agent_core/tools/args.py+++ b/core/agent_core/tools/args.py@@ -67,7 +67,3 @@ def optional_bool_arg(arguments: Mapping[str, Any], name: str) -> bool:def format_number(value: float) -> str:"""``5`` for 5.0 and ``0.5`` for 0.5, as JavaScript prints numbers in Pi's messages."""return str(int(value)) if float(value).is_integer() else repr(float(value))---def os_error_text(error: OSError) -> str:- return str(error) or type(error).__name__diff --git a/core/agent_core/tools/bash.py b/core/agent_core/tools/bash.pyindex 258e98089..86e781954 100644--- a/core/agent_core/tools/bash.py+++ b/core/agent_core/tools/bash.py@@ -28,6 +28,7 @@ from core.agent_core.tools.args import ()from core.agent_core.tools.base import MAX_BYTES, MAX_LINES, JobHost, JobStatus, ToolContext, ToolResult, ToolSpecfrom core.agent_core.tools.jobs import STOP_ABORTED, STOP_TIMEOUT, JobStartError, LocalJobHost+from core.agent_core.tools.paths import os_reasonfrom core.agent_core.tools.output import JobOutputlogger = logging.getLogger(__name__)@@ -174,6 +175,8 @@ class BashTool:return error_result(str(exc))if not os.path.isdir(ctx.cwd):return error_result(f"Working directory does not exist: {ctx.cwd}\nCannot execute bash commands.")+ if not os.access(ctx.cwd, os.X_OK):+ return error_result(f"Working directory is not accessible: {ctx.cwd}\nCannot execute bash commands.")if ctx.cancel.cancelled:return error_result("Command aborted")@@ -193,7 +196,7 @@ class BashTool:return error_result(str(exc))except OSError as exc:logger.warning("Could not start a bash job", exc_info=True)- return error_result(f"Could not start the command: {exc}")+ return error_result(f"Could not start the command: {os_reason(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.diff --git a/core/agent_core/tools/edit.py b/core/agent_core/tools/edit.pyindex e75466f63..d5f015b2a 100644--- a/core/agent_core/tools/edit.py+++ b/core/agent_core/tools/edit.py@@ -9,16 +9,15 @@ replaceAll is true" clause are Avibe's.from __future__ import annotationsimport asyncio-import errnoimport jsonimport osimport refrom typing import Any, Mapping-from core.agent_core.tools.args import ToolInputError, error_result, os_error_text, str_arg, text_result+from core.agent_core.tools.args import ToolInputError, error_result, str_arg, text_resultfrom core.agent_core.tools.base import ToolContext, ToolResult, ToolSpecfrom core.agent_core.tools.edit_diff import Edit, EditError, apply_edits, generate_diff_string, generate_unified_patch-from core.agent_core.tools.paths import file_mutation_lock, resolve_to_cwd+from core.agent_core.tools.paths import errno_name, file_mutation_lock, resolve_to_cwd, target_kindfrom core.agent_core.tools.text import decode_file, encode_filefrom core.agent_core.tools.truncate import format_sizefrom core.agent_core.tools.write import write_bytes@@ -150,9 +149,17 @@ class EditTool:async with file_mutation_lock(absolute):if ctx.cancel.cancelled:return error_result("Operation aborted")+ # Pi's access check, extended to every kind of file and checked without opening it (a FIFO would block).+ try:+ kind = target_kind(absolute)+ except OSError as exc:+ return error_result(f"Could not edit file: {path}. Error code: {errno_name(exc)}.")+ if kind == "directory":+ return error_result(f"Could not edit file: {path}. Error code: EISDIR.")+ if kind == "other":+ return error_result(f"Could not edit file: {path}. It is not a regular file.")if not os.access(absolute, os.R_OK | os.W_OK):- code = errno.errorcode.get(errno.ENOENT if not os.path.exists(absolute) else errno.EACCES, "EACCES")- return error_result(f"Could not edit file: {path}. Error code: {code}.")+ return error_result(f"Could not edit file: {path}. Error code: EACCES.")try:size = os.path.getsize(absolute)if size > MAX_EDIT_BYTES:@@ -174,7 +181,7 @@ class EditTool:except EditError as exc:return error_result(str(exc))except OSError as exc:- return error_result(os_error_text(exc))+ return error_result(f"Could not edit file: {path}. Error code: {errno_name(exc)}.")result = f"Successfully replaced {len(edits)} block(s) in {path}."if max(size, len(data)) > MAX_DIFF_BYTES:diff --git a/core/agent_core/tools/job_wrapper.py b/core/agent_core/tools/job_wrapper.pyindex b4b9c3587..bf7e0eec3 100644--- a/core/agent_core/tools/job_wrapper.py+++ b/core/agent_core/tools/job_wrapper.py@@ -20,6 +20,10 @@ skips site-packages.6. If the deadline passes before the shell exits, or the wrapper itself fails,write ``stopped`` (``timeout`` or ``wrapper_error``) and end the wholeprocess group: SIGTERM, then SIGKILL after 3 s.++Every wait is bounded or watches the deadline: the decision wait (30 s), the+check just before the shell is spawned, the read loop, the wait after the+command closes its output, and the 3 s grace before SIGKILL."""from __future__ import annotations@@ -138,10 +142,13 @@ def _run(job_dir: str, proc: subprocess.Popen, log: _BoundedLog, deadline: Optiocode = proc.returncode_write_atomic(os.path.join(job_dir, "exit"), b"%d\n" % (code if code >= 0 else 128 - code))- while not eof:+ def enforce_deadline() -> None:+ # J3: the deadline holds even when no host is there to enforce it.if not exit_written and deadline is not None and time.time() >= deadline:- # J3: the deadline holds even when no host is there to enforce it._stop_group(job_dir, "timeout", proc)++ while not eof:+ enforce_deadline()ready, _, _ = select.select([fd], [], [], 0.05)if ready:chunk = os.read(fd, 65536)@@ -163,8 +170,11 @@ def _run(job_dir: str, proc: subprocess.Popen, log: _BoundedLog, deadline: Optioexit_written = Truelog.snapshot()log.snapshot(force=True)+ # The command closed its output but may still run (``exec >/dev/null``): keep the deadline while waiting.+ while not exit_written and proc.poll() is None:+ enforce_deadline()+ time.sleep(0.05)if not exit_written:- proc.wait()write_exit()@@ -189,8 +199,10 @@ def main(argv: list[str]) -> int:_run(job_dir, proc, log, deadline)except BaseException:# A wrapper that cannot follow its command (a full disk, a bug) must not leave it running unmanaged.- traceback.print_exc()- sys.stderr.flush()+ # The diagnostics may fail for the same reason (ENOSPC), so they can never stand in the way.+ with contextlib.suppress(BaseException):+ traceback.print_exc()+ sys.stderr.flush()_stop_group(job_dir, "wrapper_error", proc)return 0diff --git a/core/agent_core/tools/jobs.py b/core/agent_core/tools/jobs.pyindex 6d3c0b19e..021f2dcc0 100644--- a/core/agent_core/tools/jobs.py+++ b/core/agent_core/tools/jobs.py@@ -51,6 +51,7 @@ from typing import Any, Awaitable, Callable, Mapping, Optionalimport psutilfrom core.agent_core.tools.base import JobStatus+from core.agent_core.tools.paths import os_reasonfrom core.process_isolation import (DEFAULT_PROCESS_TERMINATE_TIMEOUT_SECONDS,KILL_SIGNAL,@@ -306,7 +307,7 @@ class LocalJobHost:)except OSError as exc:self._create_decision(job_id, _ABANDON)- raise JobStartError(f"Could not start the command: {exc}") from exc+ raise JobStartError(f"Could not start the command: {os_reason(exc)}.") from excfinally:os.close(diagnostics)self._children[job_id] = procdiff --git a/core/agent_core/tools/paths.py b/core/agent_core/tools/paths.pyindex e09895a8d..8a6f0a744 100644--- a/core/agent_core/tools/paths.py+++ b/core/agent_core/tools/paths.py@@ -8,11 +8,13 @@ Mario Zechner).from __future__ import annotationsimport asyncio+import errnoimport osimport re+import statimport unicodedatafrom contextlib import asynccontextmanager-from typing import AsyncIterator+from typing import AsyncIterator, Literalfrom urllib.parse import unquote, urlparsefrom core.agent_core.tools.args import ToolInputError@@ -98,6 +100,34 @@ def resolve_read_path(path: str, cwd: str) -> str:return resolved+FileKind = Literal["regular", "directory", "other"]++#: Why a tool refuses a file that exists but is not a regular file.+KIND_REASON = {"directory": "it is a directory", "other": "it is not a regular file"}+++def target_kind(path: str) -> FileKind:+ """What ``path`` names, following symlinks. ``stat`` never opens the file, so a FIFO cannot block it.++ Raises ``OSError`` as ``stat`` does: missing or dangling (ENOENT), a loop (ELOOP), a file used as a+ directory (ENOTDIR), no search permission (EACCES).+ """+ mode = os.stat(path).st_mode+ if stat.S_ISREG(mode):+ return "regular"+ return "directory" if stat.S_ISDIR(mode) else "other"+++def os_reason(error: OSError) -> str:+ """``No such file or directory`` → ``no such file or directory``, for ``Cannot … {path}: {reason}.``"""+ text = error.strerror or str(error) or type(error).__name__+ return text[:1].lower() + text[1:]+++def errno_name(error: OSError) -> str:+ return errno.errorcode.get(error.errno or 0, "EIO")++class _PathLock:__slots__ = ("lock", "users")diff --git a/core/agent_core/tools/read.py b/core/agent_core/tools/read.pyindex c53232a5a..5d9979488 100644--- a/core/agent_core/tools/read.py+++ b/core/agent_core/tools/read.py@@ -22,14 +22,12 @@ from core.agent_core.messages import IMAGE_MIME_TYPES, ImageBlock, TextBlockfrom core.agent_core.tools.args import (ToolInputError,error_result,- format_number,optional_line_arg,- os_error_text,str_arg,text_result,)from core.agent_core.tools.base import MAX_BYTES, MAX_LINES, ToolContext, ToolResult, ToolSpec-from core.agent_core.tools.paths import resolve_read_path+from core.agent_core.tools.paths import KIND_REASON, os_reason, resolve_read_path, target_kindfrom core.agent_core.tools.text import decode_file, shownfrom core.agent_core.tools.truncate import format_size, truncate_head@@ -41,6 +39,7 @@ ImageSink = Callable[[bytes, str, str], Union[str, Awaitable[str]]]MAX_INLINE_IMAGE_BYTES = int(4.5 * 1024 * 1024) * 3 // 4_IMAGE_SNIFF_BYTES = 4100_PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"+_BOM = b"\xef\xbb\xbf"_READ_CHUNK_BYTES = 1024 * 1024READ_DESCRIPTION = (@@ -81,6 +80,9 @@ class ReadTool:try:absolute = resolve_read_path(path, ctx.cwd)+ refusal = await asyncio.to_thread(_refusal, absolute)+ if refusal:+ return error_result(f"Cannot read {path}: {refusal}.")mime_type = await asyncio.to_thread(_sniff_image, absolute)if mime_type is not None:return await self._read_image(absolute, mime_type)@@ -89,7 +91,7 @@ class ReadTool:except _Aborted:return error_result("Operation aborted")except OSError as exc:- return error_result(os_error_text(exc))+ return error_result(f"Cannot read {path}: {os_reason(exc)}.")except ToolInputError as exc:return error_result(str(exc))@@ -127,6 +129,19 @@ class _Aborted(Exception):pass+def _refusal(absolute: str) -> Optional[str]:+ """Why ``read`` will not open ``absolute``, checked without opening it (a FIFO would block)."""+ try:+ kind = target_kind(absolute)+ except OSError as exc:+ return os_reason(exc)+ if kind != "regular":+ return KIND_REASON[kind]+ if not os.access(absolute, os.R_OK):+ return "permission denied"+ return None++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."""@@ -165,7 +180,7 @@ def _read_text(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' {shlex.quote(path)} | head -c {MAX_BYTES}]"+ f"Use bash: sed -n '{start_display}p' {shlex.quote(absolute)} | head -c {MAX_BYTES}]")details["truncation"] = truncation.to_details()elif truncation.truncated:@@ -192,8 +207,11 @@ def _read_text(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``.+ """Lines ``[start, stop)`` as Pi's ``text.split("\\n")`` gives them, without the ``\\r`` of a CRLF break,+ the file's line count, and the raw size of line ``start``.++ Avibe drops the ``\\r`` (as tau does; Pi shows it) so read's text is edit's matching view: a copied line+ can no longer end in a bare ``\\r`` that edit would read as a line break.Collection stops once the kept lines pass either cap, so the kept prefix exceeds a cap exactly whenthe whole selection does: decoding with replacement never makes text shorter than its bytes, and@@ -206,17 +224,21 @@ def _scan_lines(first_line_bytes = 0collecting = stop is None or start < stop- def collect(segment: bytes) -> None:+ def collect(segment: bytes, ends_line: bool) -> None:nonlocal kept, opened, collectingif opened != index:if lines:kept += 1lines.append(bytearray())opened = index- room = MAX_BYTES + 1 - kept+ # One more byte at a line end, for a "\r" that is dropped below.+ room = MAX_BYTES + 1 - kept + (1 if ends_line else 0)if room > 0:lines[-1] += segment[:room]kept += min(len(segment), room)+ if ends_line and len(segment) <= room and lines[-1].endswith(b"\r"):+ del lines[-1][-1]+ kept -= 1# One line beyond the cap: a final empty piece does not count as a line.if kept > MAX_BYTES or len(lines) > MAX_LINES + 1:collecting = False@@ -229,6 +251,9 @@ def _scan_lines(index += chunk.count(b"\n", pos)with open(path, "rb") as handle:+ # A UTF-8 BOM is not shown, as edit does not match it, so text read shows can be edited.+ if handle.read(len(_BOM)) != _BOM:+ handle.seek(0)while chunk := handle.read(_READ_CHUNK_BYTES):if cancelled():raise _Aborted@@ -242,7 +267,7 @@ def _scan_lines(if index == start:first_line_bytes += end - posif index >= start:- collect(chunk[pos:end])+ collect(chunk[pos:end], newline != -1)if newline == -1:pos = len(chunk)breakdiff --git a/core/agent_core/tools/write.py b/core/agent_core/tools/write.pyindex 3de84a560..f5cb049b3 100644--- a/core/agent_core/tools/write.py+++ b/core/agent_core/tools/write.py@@ -13,9 +13,9 @@ import secretsimport statfrom typing import Any, Mapping, Optional-from core.agent_core.tools.args import ToolInputError, error_result, os_error_text, str_arg, text_result+from core.agent_core.tools.args import ToolInputError, error_result, str_arg, text_resultfrom core.agent_core.tools.base import ToolContext, ToolResult, ToolSpec-from core.agent_core.tools.paths import file_mutation_lock, resolve_to_cwd+from core.agent_core.tools.paths import KIND_REASON, file_mutation_lock, os_reason, resolve_to_cwd, target_kindWRITE_DESCRIPTION = ("Write content to a file. Creates the file if it doesn't exist, overwrites if it does. Automatically creates "@@ -53,15 +53,38 @@ class WriteTool:if ctx.cancel.cancelled:return error_result("Operation aborted")try:- await asyncio.to_thread(os.makedirs, os.path.dirname(absolute), exist_ok=True)+ refusal = await asyncio.to_thread(_prepare_target, absolute)+ if refusal:+ return error_result(f"Cannot write {path}: {refusal}.")if ctx.cancel.cancelled:return error_result("Operation aborted")await asyncio.to_thread(write_text, absolute, content)except OSError as exc:- return error_result(os_error_text(exc))+ return error_result(f"Cannot write {path}: {os_reason(exc)}.")return text_result(f"Successfully wrote to {path}")+def _prepare_target(absolute: str) -> Optional[str]:+ """Why ``write`` will not replace what ``absolute`` names, or ``None`` once it may.++ The target is what the path names after symlinks: only a writable regular file is replaced; a+ missing target gets its parent directories (also behind a dangling symlink); anything else+ (a directory, FIFO, socket, device, or a file this user cannot write) is left as it is.+ """+ target = os.path.realpath(absolute)+ try:+ kind = target_kind(target)+ except FileNotFoundError:+ os.makedirs(os.path.dirname(target), exist_ok=True)+ return None+ if kind != "regular":+ return KIND_REASON[kind]+ # A rename checks the directory, not the file, so a read-only file must be refused here.+ if not os.access(target, os.W_OK):+ return "permission denied"+ return None++def write_text(path: str, content: str) -> None:"""UTF-8 without newline translation; a lone surrogate (possible from JSON) is replaced."""write_bytes(path, content.encode("utf-8", "replace"))diff --git a/tests/agent_core/tools/test_bash.py b/tests/agent_core/tools/test_bash.pyindex f6f2a68e3..c6ed71e6f 100644--- a/tests/agent_core/tools/test_bash.py+++ b/tests/agent_core/tools/test_bash.py@@ -7,6 +7,7 @@ import osimport timeimport psutil+import pytestfrom core.agent_core.cancel import CancelTokenfrom core.agent_core.tools.bash import BashTool, settle_bash_call@@ -107,6 +108,39 @@ async def test_only_the_recorded_reason_makes_a_gone_job_a_timeout(tmp_path, makassert result_text(result).endswith("Command terminated without an exit code")[email protected]("failure", ["cwd_missing", "cwd_not_accessible", "jobs_dir_not_writable", "shell_missing"])+async def test_a_command_that_cannot_start_has_a_defined_result(tmp_path, make_ctx, failure):+ if failure != "cwd_missing" and hasattr(os, "geteuid") and os.geteuid() == 0:+ pytest.skip("root ignores file modes")+ cwd, jobs_dir, shell = tmp_path, tmp_path / "jobs", None+ if failure == "cwd_missing":+ cwd = tmp_path / "gone"+ elif failure == "cwd_not_accessible":+ cwd = tmp_path / "locked"+ cwd.mkdir(mode=0o000)+ elif failure == "jobs_dir_not_writable":+ jobs_dir.mkdir(mode=0o555)+ else:+ shell = str(tmp_path / "no-such-shell")+ locked = {"cwd_not_accessible": cwd, "jobs_dir_not_writable": jobs_dir}.get(failure)+ try:+ host = LocalJobHost(str(jobs_dir), shell=shell)+ result = await BashTool(host).execute({"command": f"touch {tmp_path / 'ran'}"}, make_ctx(cwd=str(cwd)))+ finally:+ if locked is not None:+ os.chmod(locked, 0o755)++ expected = {+ "cwd_missing": f"Working directory does not exist: {cwd}\nCannot execute bash commands.",+ "cwd_not_accessible": f"Working directory is not accessible: {cwd}\nCannot execute bash commands.",+ "jobs_dir_not_writable": "Could not start the command: permission denied.",+ # The wrapper cannot spawn the shell: it records wrapper_error and the job ends without an exit code.+ "shell_missing": "(no output)\n\nCommand terminated without an exit code",+ }[failure]+ assert (result.is_error, result_text(result)) == (True, expected)+ assert not (tmp_path / "ran").exists()++async def test_stdin_is_closed(tmp_path, make_ctx):started = time.monotonic()result = await BashTool(_host(tmp_path)).execute({"command": 'read x; echo "rc=$?"'}, make_ctx())diff --git a/tests/agent_core/tools/test_file_kinds.py b/tests/agent_core/tools/test_file_kinds.pynew file mode 100644index 000000000..826b3141d--- /dev/null+++ b/tests/agent_core/tools/test_file_kinds.py@@ -0,0 +1,190 @@+"""The OS-edge table in the PR: every kind of file the file tools can meet, and the defined result for each.++A row that would block (a FIFO) or replace something that is not a regular file must not; every+other row gets one error text, written the same way for every kind.+"""++from __future__ import annotations++import asyncio+import os+import shutil+import socket+import stat+import tempfile++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++KINDS = [+ "regular",+ "read_only",+ "unreadable",+ "directory",+ "fifo",+ "socket",+ "device",+ "link_regular",+ "link_directory",+ "link_device",+ "dangling",+ "missing",+ "loop",+]+NOT_REGULAR = {"fifo", "socket", "device", "link_device"}+DIRECTORY = {"directory", "link_directory"}+ABSENT = {"dangling", "missing"}+NOT_ROOT = pytest.mark.skipif(hasattr(os, "geteuid") and os.geteuid() == 0, reason="root ignores file modes")+++def place(tmp_path):+ """Build one kind of file and return the path a model would pass for it."""+ cleanups = []++ def make(kind: str) -> str:+ if kind in ("regular", "read_only", "unreadable"):+ (tmp_path / "f").write_text("hello\n")+ mode = {"regular": 0o644, "read_only": 0o444, "unreadable": 0o000}[kind]+ os.chmod(tmp_path / "f", mode)+ cleanups.append(lambda: os.chmod(tmp_path / "f", 0o644))+ return "f"+ if kind == "directory":+ (tmp_path / "d").mkdir()+ return "d"+ if kind == "fifo":+ os.mkfifo(tmp_path / "p")+ return "p"+ if kind == "socket":+ # Unix socket paths are short; a private directory under /tmp keeps it under the limit.+ directory = tempfile.mkdtemp(prefix="avs", dir="/tmp")+ server = socket.socket(socket.AF_UNIX)+ server.bind(os.path.join(directory, "s"))+ cleanups.append(server.close)+ cleanups.append(lambda: shutil.rmtree(directory, ignore_errors=True))+ return os.path.join(directory, "s")+ if kind == "device":+ return os.devnull+ if kind == "link_regular":+ (tmp_path / "f").write_text("hello\n")+ (tmp_path / "l").symlink_to(tmp_path / "f")+ return "l"+ if kind == "link_directory":+ (tmp_path / "d").mkdir()+ (tmp_path / "l").symlink_to(tmp_path / "d")+ return "l"+ if kind == "link_device":+ (tmp_path / "l").symlink_to(os.devnull)+ return "l"+ if kind == "dangling":+ (tmp_path / "l").symlink_to(tmp_path / "missing" / "f")+ return "l"+ if kind == "missing":+ return "missing/sub/f"+ assert kind == "loop"+ (tmp_path / "l").symlink_to(tmp_path / "l2")+ (tmp_path / "l2").symlink_to(tmp_path / "l")+ return "l"++ yield make+ for cleanup in reversed(cleanups):+ cleanup()+++async def _run(tool, arguments, ctx, tmp_path):+ """Run the tool; a FIFO that blocks it fails the row, and is unblocked so no thread is left behind."""+ task = asyncio.ensure_future(tool.execute(arguments, ctx))+ try:+ return await asyncio.wait_for(asyncio.shield(task), timeout=5)+ except asyncio.TimeoutError:+ # Each blocked open of the FIFO needs a writer to come and go; give it one until the tool returns.+ fifo = tmp_path / "p"+ for _ in range(100):+ if task.done():+ break+ try:+ os.close(os.open(fifo, os.O_WRONLY | os.O_NONBLOCK))+ except OSError:+ pass+ await asyncio.sleep(0.05)+ pytest.fail("the tool blocked on a file it should not have opened")+++def _cases(kinds):+ return [pytest.param(kind, marks=NOT_ROOT) if kind == "unreadable" else kind for kind in kinds]++[email protected]("kind", _cases(KINDS))+async def test_read_has_a_defined_result_for_every_kind(tmp_path, make_ctx, place, kind):+ path = place(kind)++ result = await _run(ReadTool(), {"path": path}, make_ctx(), tmp_path)++ if kind in ("regular", "read_only", "link_regular"):+ assert (result.is_error, result_text(result)) == (False, "hello\n")+ return+ reason = {+ "unreadable": "permission denied",+ "loop": "too many levels of symbolic links",+ **dict.fromkeys(DIRECTORY, "it is a directory"),+ **dict.fromkeys(NOT_REGULAR, "it is not a regular file"),+ **dict.fromkeys(ABSENT, "no such file or directory"),+ }[kind]+ assert (result.is_error, result_text(result)) == (True, f"Cannot read {path}: {reason}.")++[email protected]("kind", _cases(KINDS))+async def test_write_has_a_defined_result_for_every_kind(tmp_path, make_ctx, place, kind):+ path = place(kind)+ before = os.lstat(path if os.path.isabs(path) else tmp_path / path).st_mode if kind not in ABSENT else None++ result = await _run(WriteTool(), {"path": path, "content": "new\n"}, make_ctx(), tmp_path)++ if kind in ("regular", "link_regular", "dangling", "missing"):+ assert (result.is_error, result_text(result)) == (False, f"Successfully wrote to {path}")+ target = {"regular": "f", "link_regular": "f", "dangling": "missing/f", "missing": "missing/sub/f"}[kind]+ assert (tmp_path / target).read_text() == "new\n"+ if kind in ("link_regular", "dangling"):+ assert (tmp_path / path).is_symlink()+ return+ reason = {+ "read_only": "permission denied",+ "unreadable": "permission denied",+ "loop": "too many levels of symbolic links",+ **dict.fromkeys(DIRECTORY, "it is a directory"),+ **dict.fromkeys(NOT_REGULAR, "it is not a regular file"),+ }[kind]+ assert (result.is_error, result_text(result)) == (True, f"Cannot write {path}: {reason}.")+ # Nothing that is not a writable regular file is ever replaced.+ assert os.lstat(path if os.path.isabs(path) else tmp_path / path).st_mode == before+ if kind == "read_only":+ assert (tmp_path / "f").read_text() == "hello\n"++[email protected]("kind", _cases(KINDS))+async def test_edit_has_a_defined_result_for_every_kind(tmp_path, make_ctx, place, kind):+ path = place(kind)+ arguments = {"path": path, "edits": [{"oldText": "hello", "newText": "bye"}]}++ result = await _run(EditTool(), arguments, make_ctx(), tmp_path)++ if kind in ("regular", "link_regular"):+ assert (result.is_error, result_text(result)) == (False, f"Successfully replaced 1 block(s) in {path}.")+ assert (tmp_path / "f").read_text() == "bye\n"+ assert (tmp_path / path).is_symlink() == (kind == "link_regular")+ return+ detail = {+ "read_only": "Error code: EACCES.",+ "unreadable": "Error code: EACCES.",+ "loop": "Error code: ELOOP.",+ **dict.fromkeys(DIRECTORY, "Error code: EISDIR."),+ **dict.fromkeys(NOT_REGULAR, "It is not a regular file."),+ **dict.fromkeys(ABSENT, "Error code: ENOENT."),+ }[kind]+ assert (result.is_error, result_text(result)) == (True, f"Could not edit file: {path}. {detail}")+ if kind == "read_only":+ assert stat.S_IMODE(os.stat(tmp_path / "f").st_mode) == 0o444diff --git a/tests/agent_core/tools/test_jobs.py b/tests/agent_core/tools/test_jobs.pyindex 4a2c6c51e..69fbe9046 100644--- a/tests/agent_core/tools/test_jobs.py+++ b/tests/agent_core/tools/test_jobs.py@@ -9,6 +9,7 @@ production.from __future__ import annotationsimport asyncio+import errnoimport osimport subprocessimport time@@ -278,6 +279,50 @@ async def test_a_deadline_that_passed_during_the_launch_never_starts_the_commandassert host.stop_reason(job_id) == "timeout"+async def test_the_deadline_holds_after_the_command_closes_its_output(tmp_path):+ """A command that closes stdout and stderr and keeps running is still stopped at its deadline (J3)."""+ host = LocalJobHost(str(tmp_path / "jobs"))+ job_id = await _start(+ host, tmp_path, f"echo $$ > {tmp_path / 'sh.pid'}; exec >/dev/null 2>&1; sleep 20", timeout_s=0.5+ )+ del host # nobody waits on the job from here on++ stopped = _wait_until(lambda: _wrapper_gone(str(tmp_path / "jobs" / job_id)), timeout_s=6)+ restarted = LocalJobHost(str(tmp_path / "jobs"))+ if not stopped:+ await restarted.kill(job_id)+ assert stopped+ assert restarted.stop_reason(job_id) == "timeout"+++def test_the_wrapper_stops_its_group_even_when_its_diagnostics_fail(tmp_path, monkeypatch):+ """The wrapper's own failure handler must stop the command even if writing the traceback fails (ENOSPC)."""+ import core.agent_core.tools.job_wrapper as wrapper++ class Stopped(BaseException):+ pass++ def full_disk(*args, **kwargs):+ raise OSError(errno.ENOSPC, "No space left on device")++ stops = []++ def stop_group(job_dir, reason, proc):+ stops.append(reason)+ raise Stopped # the real one ends the process group and never returns++ monkeypatch.setattr(wrapper, "_wait_for_decision", lambda job_dir, timeout_s: "go")+ monkeypatch.setattr(wrapper, "_BoundedLog", full_disk)+ monkeypatch.setattr(wrapper.traceback, "print_exc", full_disk)+ monkeypatch.setattr(wrapper, "_stop_group", stop_group)+ argv = ["job_wrapper.py", "avibe-job", str(tmp_path), "/bin/sh", "true", "30", "10", "10", "-"]++ with pytest.raises(Stopped):+ wrapper.main(argv)++ assert stops == ["wrapper_error"]++async def test_job_files_stay_until_the_call_is_settled(tmp_path):"""J5."""host = LocalJobHost(str(tmp_path / "jobs"))diff --git a/tests/agent_core/tools/test_read.py b/tests/agent_core/tools/test_read.pyindex f72dd45bc..514679250 100644--- a/tests/agent_core/tools/test_read.py+++ b/tests/agent_core/tools/test_read.py@@ -2,7 +2,9 @@from __future__ import annotations+import osimport random+import shleximport structimport zlib@@ -68,12 +70,23 @@ async def test_offset_and_limit_are_integers_of_at_least_one(tmp_path, make_ctx,assert result_text(result) == f"{message} must be an integer of at least 1"-async def test_an_over_long_first_line_points_at_bash(tmp_path, make_ctx):- (tmp_path / "big file.txt").write_text("short\n" + "x" * 61_440 + "\nafter\n")-- text = result_text(await _read(make_ctx, path="big file.txt", offset=2))+ "spelling", ["big file.txt", "~/big file.txt", "file://{home}/big%20file.txt", "@big file.txt"]+)+async def test_an_over_long_first_line_points_at_bash_with_the_file_read_opened(tmp_path, make_ctx, spelling):+ """The suggested command names the resolved file, so it runs whatever spelling the model used."""+ home = os.path.expanduser("~")+ os.makedirs(home, exist_ok=True)+ target = os.path.join(home, "big file.txt")+ with open(target, "w") as handle:+ handle.write("short\n" + "x" * 61_440 + "\nafter\n")++ result = await ReadTool().execute({"path": spelling.format(home=home), "offset": 2}, make_ctx(cwd=home))+ text = result_text(result)- assert text == "[Line 2 is 60.0KB, exceeds 50.0KB limit. Use bash: sed -n '2p' 'big file.txt' | head -c 51200]"+ assert text == (+ f"[Line 2 is 60.0KB, exceeds 50.0KB limit. Use bash: sed -n '2p' {shlex.quote(target)} | head -c 51200]"+ )class _CancelledAfter(CancelToken):@@ -102,6 +115,8 @@ async def test_cancel_stops_a_long_scan(tmp_path, make_ctx, monkeypatch):def _whole_file_read(data: bytes, start: int, stop):"""Pi's algorithm on the whole file, as the oracle for the streamed reader."""lines = data.decode("utf-8", "replace").split("\n")+ # The "\r" of a CRLF break is not shown.+ lines = [line[:-1] if line.endswith("\r") and i < len(lines) - 1 else line for i, line in enumerate(lines)]return truncate_head("\n".join(lines[start:stop]), max_lines=5, max_bytes=20), len(lines)diff --git a/tests/agent_core/tools/test_write_edit.py b/tests/agent_core/tools/test_write_edit.pyindex 778d0705f..56b7a7e91 100644--- a/tests/agent_core/tools/test_write_edit.py+++ b/tests/agent_core/tools/test_write_edit.py@@ -112,6 +112,19 @@ async def test_text_copied_from_read_edits_a_file_with_invalid_bytes(tmp_path, massert (tmp_path / "f.txt").read_bytes() == b"fixed\nkeep\x80\n"+async def test_text_copied_from_read_edits_the_first_line_of_a_bom_file(tmp_path, make_ctx):+ """read does not show the BOM, edit does not match it, and the BOM survives."""+ (tmp_path / "f.txt").write_bytes(b"\xef\xbb\xbfalpha\r\nbeta\r\n")+ shown = result_text(await ReadTool().execute({"path": "f.txt"}, make_ctx()))+ first_line = shown.split("\n")[0]++ result = await _edit(make_ctx, "f.txt", {"oldText": first_line, "newText": "ALPHA"})++ assert shown == "alpha\nbeta\n"+ assert not result.is_error, result_text(result)+ assert (tmp_path / "f.txt").read_bytes() == b"\xef\xbb\xbfALPHA\r\nbeta\r\n"++async def test_a_planned_result_over_the_limit_is_refused_and_its_diff_skipped(tmp_path, make_ctx, monkeypatch):(tmp_path / "small.txt").write_text("seed\n")monkeypatch.setattr(edit_module, "MAX_EDIT_BYTES", 1000)