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): revalidate write targets before publishing, bound both kept segments, short temp names
cyhf5ce6e895bec
diff --git a/core/agent_core/tools/normalize.py b/core/agent_core/tools/normalize.pyindex 5b7312633..0310595e3 100644--- a/core/agent_core/tools/normalize.py+++ b/core/agent_core/tools/normalize.py@@ -28,6 +28,14 @@ _ANSI_RE = re.compile(_MAX_OPEN_CHARS = 64 * 1024+def _bounded(segment: str, dropped: int) -> tuple[str, int]:+ """``segment``'s last ``_MAX_OPEN_CHARS`` characters, and the UTF-8 bytes dropped from its start."""+ if len(segment) <= _MAX_OPEN_CHARS:+ return segment, dropped+ cut = len(segment) - _MAX_OPEN_CHARS+ return segment[cut:], dropped + utf8_len(segment[:cut])++def strip_ansi(text: str) -> str:return _ANSI_RE.sub("", text).replace("\x1b", "")@@ -106,15 +114,10 @@ class OutputNormalizer:# The first piece continues the current segment, so it keeps that segment's drop count.for index in range(len(segments) - 2, -1, -1):if strip_ansi(segments[index]):- self._prev = segments[index]- self._prev_dropped = self._cur_dropped if index == 0 else 0+ self._prev, self._prev_dropped = _bounded(segments[index], self._cur_dropped if index == 0 else 0)breakself._cur_dropped = 0- self._cur = segments[-1]- if len(self._cur) > _MAX_OPEN_CHARS:- cut = len(self._cur) - _MAX_OPEN_CHARS- self._cur_dropped += utf8_len(self._cur[:cut])- self._cur = self._cur[cut:]+ self._cur, self._cur_dropped = _bounded(segments[-1], self._cur_dropped)def _line(self) -> str:return self._line_and_size()[0]diff --git a/core/agent_core/tools/write.py b/core/agent_core/tools/write.pyindex e36af3e96..d08255ef2 100644--- a/core/agent_core/tools/write.py+++ b/core/agent_core/tools/write.py@@ -7,6 +7,7 @@ Ported from Pi ``packages/coding-agent/src/core/tools/write.ts`` (MIT, Copyrightfrom __future__ import annotationsimport contextlib+import errnoimport osimport secretsimport stat@@ -17,6 +18,7 @@ from core.agent_core.tools.args import ToolInputError, error_result, str_arg, tefrom core.agent_core.tools.base import ToolContext, ToolResult, ToolSpecfrom core.agent_core.tools.paths import (KIND_REASON,+ NotRegularFile,file_mutation_lock,os_reason,resolve_to_cwd,@@ -70,6 +72,8 @@ class WriteTool:return error_result(f"Cannot write {path}: its directory is not writable, so the file cannot be replaced safely.")+ except NotRegularFile as exc:+ return error_result(f"Cannot write {path}: {KIND_REASON[exc.kind]}.")except OSError as exc:return error_result(f"Cannot write {path}: {os_reason(exc)}.")return text_result(f"Successfully wrote to {path}")@@ -132,6 +136,21 @@ def _require(expected: Optional[FileIdentity], path: str, st: os.stat_result) ->raise FileChanged()+def _check_publishable(current: str, expected: Optional[FileIdentity]) -> None:+ """Right before the rename: ``current`` is absent, or a writable regular file (the one that was read)."""+ try:+ st = os.stat(current)+ except FileNotFoundError:+ if expected is not None:+ raise FileChanged() from None+ return+ if not stat.S_ISREG(st.st_mode):+ raise NotRegularFile("directory" if stat.S_ISDIR(st.st_mode) else "other")+ if not os.access(current, os.W_OK):+ raise PermissionError(errno.EACCES, os.strerror(errno.EACCES), current)+ _require(expected, current, st)++def write_bytes(path: str, data: bytes, expected: Optional[FileIdentity] = None) -> None:"""Create or replace ``path`` only once ``data`` is completely on disk.@@ -145,14 +164,17 @@ def write_bytes(path: str, data: bytes, expected: Optional[FileIdentity] = None)(``NotReplaceable``) rather than written in place, which a full disk could leave half-written.With ``expected``, the file must still be the one that was read, checked once right before the- rename. POSIX has no compare-and-rename, so a change between that check and the rename is not seen.+ rename. Without it, the target is checked there again as ``write`` first classified it: absent, or a+ writable regular file, so a file swapped for a FIFO, a directory, or a read-only file is never+ replaced. POSIX has no compare-and-rename, so a change between that check and the rename is not seen."""target = os.path.realpath(path)try:mode: Optional[int] = stat.S_IMODE(os.stat(target).st_mode)except FileNotFoundError:mode = None- tmp = os.path.join(os.path.dirname(target), f".{os.path.basename(target)}.{secrets.token_hex(4)}.tmp")+ # Short and not derived from the target's name, which may already be at NAME_MAX.+ tmp = os.path.join(os.path.dirname(target), f".avibe-{secrets.token_hex(6)}.tmp")try:fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600 if mode is not None else 0o666)except PermissionError:@@ -166,12 +188,7 @@ def write_bytes(path: str, data: bytes, expected: Optional[FileIdentity] = None)os.fsync(handle.fileno())if mode is not None:os.fchmod(handle.fileno(), mode)- if expected is not None:- current = os.path.realpath(path)- try:- _require(expected, current, os.stat(current))- except FileNotFoundError:- raise FileChanged() from None+ _check_publishable(os.path.realpath(path) if expected is not None else target, expected)os.replace(tmp, target)except BaseException:with contextlib.suppress(FileNotFoundError):diff --git a/tests/agent_core/tools/test_normalize.py b/tests/agent_core/tools/test_normalize.pyindex 8bfef334b..4a7ed3c49 100644--- a/tests/agent_core/tools/test_normalize.py+++ b/tests/agent_core/tools/test_normalize.py@@ -43,3 +43,15 @@ def test_a_long_final_line_keeps_its_end_and_says_what_was_dropped():out = "".join(normalizer.feed(b"y" * 10_000) for _ in range(10)) + normalizer.feed(b"\n") + normalizer.flush()assert out == f"[... {100_000 - 65_536} bytes omitted ...]" + "y" * 65_536 + "\n"++[email protected]("after", [b"\r\r", b"\r\x1b[0m"], ids=["two-returns", "ansi-only-redraw"])+def test_a_segment_kept_for_a_redraw_is_bounded_too(after):+ """Both kept segments of an open line obey the bound: the one a redraw may fall back to as well."""+ normalizer = OutputNormalizer()++ normalizer.feed(b"x" * 200_000 + after)+ open_line = normalizer.peek()+ out = normalizer.flush()++ assert open_line == out == f"[... {200_000 - 65_536} bytes omitted ...]" + "x" * 65_536diff --git a/tests/agent_core/tools/test_write_edit.py b/tests/agent_core/tools/test_write_edit.pyindex 82cf819d7..349ddedad 100644--- a/tests/agent_core/tools/test_write_edit.py+++ b/tests/agent_core/tools/test_write_edit.py@@ -281,6 +281,53 @@ async def test_an_edit_publishes_only_over_the_file_it_read(tmp_path, make_ctx,assert (real.read_text(), other.read_text()) == expected[email protected]("swap", ["fifo", "read-only", "directory"])+async def test_write_revalidates_the_target_right_before_replacing_it(tmp_path, make_ctx, monkeypatch, swap):+ """Another process swapped the file after write classified it: nothing that is not a writable regular file+ is ever replaced."""+ (tmp_path / "f").write_text("old\n")+ real_prepare = write_module._prepare_target++ def prepare_then_swap(absolute):+ refusal = real_prepare(absolute)+ os.remove(absolute)+ if swap == "fifo":+ os.mkfifo(absolute)+ elif swap == "read-only":+ with open(absolute, "w") as handle:+ handle.write("theirs\n")+ os.chmod(absolute, 0o444)+ else:+ os.mkdir(absolute)+ return refusal++ monkeypatch.setattr(write_module, "_prepare_target", prepare_then_swap)+ result = await WriteTool().execute({"path": "f", "content": "new\n"}, make_ctx())++ reason = {"fifo": "it is not a regular file", "read-only": "permission denied", "directory": "it is a directory"}+ assert (result.is_error, result_text(result)) == (True, f"Cannot write f: {reason[swap]}.")+ kind = os.lstat(tmp_path / "f").st_mode+ assert {"fifo": stat.S_ISFIFO, "read-only": stat.S_ISREG, "directory": stat.S_ISDIR}[swap](kind)+ if swap == "read-only":+ assert (tmp_path / "f").read_text() == "theirs\n"+ assert [p.name for p in tmp_path.iterdir()] == ["f"]++[email protected]("tool", ["write", "edit"])+async def test_a_name_at_the_length_limit_can_be_replaced(tmp_path, make_ctx, tool):+ """The temp file beside the target must not be longer than the target's own (valid) name."""+ name = "n" * 251 + ".txt" # 255 bytes, the usual NAME_MAX+ (tmp_path / name).write_text("old\n")++ if tool == "write":+ result = await WriteTool().execute({"path": name, "content": "new\n"}, make_ctx())+ else:+ result = await _edit(make_ctx, name, {"oldText": "old", "newText": "new"})++ assert not result.is_error, result_text(result)+ assert (tmp_path / name).read_text() == "new\n"++async def test_new_files_keep_the_umask_default(tmp_path, make_ctx):umask = os.umask(0)os.umask(umask)