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): one output-log label, bounded image sniffing, line-bounded diffs

cyh64003c64069c
diff --git a/core/agent_core/tools/edit.py b/core/agent_core/tools/edit.py
index 2f9525be8..8a74c3c09 100644
--- a/core/agent_core/tools/edit.py
+++ b/core/agent_core/tools/edit.py
@@ -15,7 +15,7 @@ from typing import Any, Mapping
from core.agent_core.tools.args import ToolInputError, error_result, str_arg, text_result
from core.agent_core.tools.base import ToolContext, ToolResult, ToolSpec
-from core.agent_core.tools.edit_diff import Edit, EditError, apply_edits, generate_diff_string, generate_unified_patch
+from core.agent_core.tools.edit_diff import Edit, EditError, apply_edits, display_diff
from core.agent_core.tools.paths import (
NotRegularFile,
errno_name,
@@ -211,6 +211,8 @@ class EditTool:
if max(size, len(data)) > MAX_DIFF_BYTES:
# The diff is for display only, and difflib is superlinear on large inputs.
return text_result(result, details={"diff_skipped": True})
- diff, first_changed_line = await asyncio.to_thread(generate_diff_string, base, new_content)
- patch = await asyncio.to_thread(generate_unified_patch, path, base, new_content)
+ shown_diff = await asyncio.to_thread(display_diff, path, base, new_content)
+ if shown_diff is None:
+ return text_result(result, details={"diff_skipped": True})
+ diff, first_changed_line, patch = shown_diff
return text_result(result, details={"diff": diff, "patch": patch, "first_changed_line": first_changed_line})
diff --git a/core/agent_core/tools/edit_diff.py b/core/agent_core/tools/edit_diff.py
index 7210a6d5a..b6e83b1f1 100644
--- a/core/agent_core/tools/edit_diff.py
+++ b/core/agent_core/tools/edit_diff.py
@@ -308,20 +308,80 @@ def apply_edits(text: str, edits: list[Edit], path: str) -> tuple[str, str, str]
return new_text, lines.view, _Lines(new_text).view
-def generate_unified_patch(path: str, old: str, new: str, context: int = 4) -> str:
- lines = difflib.unified_diff(
- old.splitlines(keepends=True), new.splitlines(keepends=True), fromfile=path, tofile=path, n=context
- )
- return "".join(lines)
+#: The display diff runs difflib only on the changed middle, and skips it when either side is longer.
+DIFF_MAX_LINES = 1000
+
+
+class _FixedOpcodes(difflib.SequenceMatcher):
+ """difflib's hunk grouping over opcodes computed elsewhere."""
+
+ def __init__(self, a: list[str], b: list[str], opcodes: list[tuple[str, int, int, int, int]]) -> None:
+ super().__init__(None, a, b)
+ self._fixed = opcodes
+ def get_opcodes(self) -> list[tuple[str, int, int, int, int]]: # type: ignore[override]
+ return self._fixed
-def generate_diff_string(old: str, new: str, context: int = 4) -> tuple[str, Optional[int]]:
+
+def display_diff(path: str, old: str, new: str, context: int = 4) -> Optional[tuple[str, Optional[int], str]]:
+ """``(diff, first_changed_line, patch)`` for display, or ``None`` when the change is too large to show.
+
+ The common leading and trailing lines are trimmed in linear time, and difflib (whose worst case
+ is quadratic, for example on repetitive lines) sees only the changed middle, at most
+ ``DIFF_MAX_LINES`` lines on each side.
+ """
+ a, b = old.splitlines(keepends=True), new.splitlines(keepends=True)
+ shortest = min(len(a), len(b))
+ prefix = 0
+ while prefix < shortest and a[prefix] == b[prefix]:
+ prefix += 1
+ suffix = 0
+ while suffix < shortest - prefix and a[len(a) - 1 - suffix] == b[len(b) - 1 - suffix]:
+ suffix += 1
+ a_end, b_end = len(a) - suffix, len(b) - suffix
+ if a_end - prefix > DIFF_MAX_LINES or b_end - prefix > DIFF_MAX_LINES:
+ return None
+ middle = difflib.SequenceMatcher(None, a[prefix:a_end], b[prefix:b_end]).get_opcodes()
+ opcodes = [("equal", 0, prefix, 0, prefix)] if prefix else []
+ opcodes += [(tag, i1 + prefix, i2 + prefix, j1 + prefix, j2 + prefix) for tag, i1, i2, j1, j2 in middle]
+ if suffix:
+ opcodes.append(("equal", a_end, len(a), b_end, len(b)))
+ diff, first_changed_line = _render_diff(a, b, opcodes, context)
+ return diff, first_changed_line, _unified_patch(path, a, b, opcodes, context)
+
+
+def _unified_range(start: int, stop: int) -> str:
+ length = stop - start
+ if length == 1:
+ return str(start + 1)
+ return f"{start + 1 if length else start},{length}"
+
+
+def _unified_patch(path: str, a: list[str], b: list[str], opcodes: list, context: int) -> str:
+ """``difflib.unified_diff``'s output, from the given opcodes."""
+ groups = list(_FixedOpcodes(a, b, opcodes).get_grouped_opcodes(context))
+ if not groups:
+ return ""
+ out = [f"--- {path}\n", f"+++ {path}\n"]
+ for group in groups:
+ first, last = group[0], group[-1]
+ out.append(f"@@ -{_unified_range(first[1], last[2])} +{_unified_range(first[3], last[4])} @@\n")
+ for tag, i1, i2, j1, j2 in group:
+ if tag == "equal":
+ out.extend(" " + line for line in a[i1:i2])
+ continue
+ out.extend("-" + line for line in a[i1:i2])
+ out.extend("+" + line for line in b[j1:j2])
+ return "".join(out)
+
+
+def _render_diff(a: list[str], b: list[str], opcodes: list, context: int) -> tuple[str, Optional[int]]:
"""Pi's display diff: numbered ``+``/``-``/context lines and the first changed line of the new file."""
- old_lines, new_lines = old.split("\n"), new.split("\n")
- width = len(str(max(len(old_lines), len(new_lines))))
+ a = [line.rstrip("\r\n") for line in a]
+ b = [line.rstrip("\r\n") for line in b]
+ width = len(str(max(len(a), len(b)) + 1))
parts: list[tuple[str, list[str]]] = []
- a, b = old.splitlines(), new.splitlines()
- for tag, i1, i2, j1, j2 in difflib.SequenceMatcher(None, a, b, autojunk=False).get_opcodes():
+ for tag, i1, i2, j1, j2 in opcodes:
if tag == "equal":
parts.append((" ", a[i1:i2]))
continue
diff --git a/core/agent_core/tools/output.py b/core/agent_core/tools/output.py
index c5e512063..1a7e12660 100644
--- a/core/agent_core/tools/output.py
+++ b/core/agent_core/tools/output.py
@@ -164,10 +164,12 @@ class JobOutput:
return f"{text}\n\n{notice}", truncation
def where(self) -> str:
- """Where the log is. ``Full output`` only for a finished job whose log was never bounded on disk (J4):
- a running job's log may still pass the cap."""
- if self._finished and not self._omitted:
- return f"Full output: {self.path}"
+ """Where the log is, in one wording for every state (C-7 section 5).
+
+ The log keeps everything up to the cap and drops the middle beyond it, and a job can keep
+ appending after its result was built (a background child holding the pipe), so the label states
+ that policy rather than the log's current state: it can never become untrue.
+ """
cap = format_size(job_host.OUTPUT_HEAD_BYTES + job_host.OUTPUT_TAIL_BYTES)
return f"Output log (middle omitted beyond {cap}): {self.path}"
diff --git a/core/agent_core/tools/read.py b/core/agent_core/tools/read.py
index 6eab1c9ae..53254bce8 100644
--- a/core/agent_core/tools/read.py
+++ b/core/agent_core/tools/read.py
@@ -148,40 +148,39 @@ def _load(
absolute: str, path: str, offset: Optional[int], limit: Optional[int], cancelled: Callable[[], bool]
) -> Union[ToolResult, _Image]:
"""Everything read takes from the file, through one descriptor: the kind, the image type, the size,
- and the bytes. A file swapped or grown after an earlier check by path cannot get past its limits."""
+ and the bytes. A file swapped or grown after an earlier check by path cannot get past its limits,
+ and image work never looks past the bytes the cap allows."""
with os.fdopen(open_regular(absolute), "rb") as handle:
- mime_type = _sniff_image(handle)
+ head = handle.read(_IMAGE_SNIFF_BYTES)
+ mime_type = _sniff_image(head)
if mime_type is None:
return _read_text(handle, absolute, path, offset, limit, cancelled)
- header = f"Read image file [{mime_type}]"
- details = {"path": absolute, "mime_type": mime_type}
- if mime_type not in IMAGE_MIME_TYPES:
- # Pi converts other formats to PNG; without an image library Avibe cannot.
- return text_result(
- f"{header}\n[Image omitted: could not be converted to a supported inline image format.]",
- details=details,
- )
- handle.seek(0)
- data = handle.read(MAX_INLINE_IMAGE_BYTES + 1)
- size = max(os.fstat(handle.fileno()).st_size, len(data))
- if size > MAX_INLINE_IMAGE_BYTES:
- # Avibe: no resizing in v1.
- return text_result(
- f"{header}\n[Image omitted: the file is {format_size(size)}, over the "
- f"{format_size(MAX_INLINE_IMAGE_BYTES)} inline image limit. Images are not resized.]",
- details={**details, "bytes": size},
- )
- return _Image(mime_type, data, len(data))
+ if mime_type in IMAGE_MIME_TYPES:
+ data = head + handle.read(max(0, MAX_INLINE_IMAGE_BYTES + 1 - len(head)))
+ size = max(os.fstat(handle.fileno()).st_size, len(data))
+ if size > MAX_INLINE_IMAGE_BYTES:
+ # Avibe: no resizing in v1.
+ return text_result(
+ f"Read image file [{mime_type}]\n[Image omitted: the file is {format_size(size)}, over the "
+ f"{format_size(MAX_INLINE_IMAGE_BYTES)} inline image limit. Images are not resized.]",
+ details={"path": absolute, "mime_type": mime_type, "bytes": size},
+ )
+ if mime_type == "image/png" and _png_is_animated(data):
+ # acTL may sit past the sniffed prefix, behind large ancillary chunks.
+ mime_type = "image/apng"
+ else:
+ return _Image(mime_type, data, len(data))
+ # Pi converts other formats to PNG; without an image library Avibe cannot.
+ return text_result(
+ f"Read image file [{mime_type}]\n[Image omitted: could not be converted to a supported inline image format.]",
+ details={"path": absolute, "mime_type": mime_type},
+ )
-def _sniff_image(handle: BinaryIO) -> Optional[str]:
- """The image type to attach, or ``None`` for text. A PNG or JPEG Pi cannot send (animated PNG,
+def _sniff_image(head: bytes) -> Optional[str]:
+ """The image type ``head`` shows, 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."""
- head = handle.read(_IMAGE_SNIFF_BYTES)
supported = detect_supported_image_mime_type(head)
- if supported == "image/png" and _png_file_is_animated(handle):
- # acTL may sit past the sniffed prefix, behind large ancillary chunks.
- return "image/apng"
if supported is not None:
return supported
if head.startswith(_PNG_SIGNATURE):
@@ -191,6 +190,19 @@ def _sniff_image(handle: BinaryIO) -> Optional[str]:
return None
+def _png_is_animated(data: bytes) -> bool:
+ """Walk the chunk headers of ``data`` (at most the image cap, already read) until IDAT or acTL."""
+ offset = len(_PNG_SIGNATURE)
+ while offset + 8 <= len(data):
+ length, kind = struct.unpack(">I", data[offset : offset + 4])[0], data[offset + 4 : offset + 8]
+ if kind == b"acTL":
+ return True
+ if kind == b"IDAT":
+ return False
+ offset += 12 + length
+ return False
+
+
def _read_text(
handle: BinaryIO,
absolute: str,
@@ -327,24 +339,6 @@ def detect_supported_image_mime_type(data: bytes) -> Optional[str]:
return None
-def _png_file_is_animated(handle: BinaryIO) -> bool:
- """Walk the chunk headers until IDAT or acTL, seeking over chunk bodies; bounded by the file size."""
- size = os.fstat(handle.fileno()).st_size
- offset = len(_PNG_SIGNATURE)
- while offset + 8 <= size:
- handle.seek(offset)
- header = handle.read(8)
- if len(header) < 8:
- return False
- length, kind = struct.unpack(">I", header[:4])[0], header[4:]
- if kind == b"acTL":
- return True
- if kind == b"IDAT":
- return False
- offset += 12 + length
- return False
-
-
def _is_png(data: bytes) -> bool:
return len(data) >= 16 and struct.unpack(">I", data[8:12])[0] == 13 and data[12:16] == b"IHDR"
diff --git a/tests/agent_core/tools/test_bash.py b/tests/agent_core/tools/test_bash.py
index 74068fda5..8570882b8 100644
--- a/tests/agent_core/tools/test_bash.py
+++ b/tests/agent_core/tools/test_bash.py
@@ -48,7 +48,10 @@ async def test_long_output_keeps_the_tail_and_names_the_full_output(tmp_path, ma
path = result.details["output_path"]
assert not result.is_error
- assert result_text(result).endswith(f"2499\n2500\n\n[Showing lines 501-2500 of 2500. Full output: {path}]")
+ # One label in every state: the log keeps everything up to the cap, so it is never promised as complete.
+ assert result_text(result).endswith(
+ f"2499\n2500\n\n[Showing lines 501-2500 of 2500. Output log (middle omitted beyond 3.0MB): {path}]"
+ )
assert open(path).read() == "".join(f"{i}\n" for i in range(1, 2501))
diff --git a/tests/agent_core/tools/test_read.py b/tests/agent_core/tools/test_read.py
index 2257ebdad..87875a392 100644
--- a/tests/agent_core/tools/test_read.py
+++ b/tests/agent_core/tools/test_read.py
@@ -5,6 +5,7 @@ from __future__ import annotations
import asyncio
import os
import random
+import time
import shlex
import struct
import zlib
@@ -261,3 +262,17 @@ async def test_a_fifo_swapped_in_after_the_check_does_not_block_read(tmp_path, m
pytest.fail("read blocked on a FIFO")
assert (result.is_error, result_text(result)) == (True, "Cannot read p: it is not a regular file.")
+
+
+async def test_a_huge_png_shaped_file_is_classified_without_walking_it(tmp_path, make_ctx):
+ """A sparse file of empty PNG chunks: image work is bounded by the cap, not by the file."""
+ path = tmp_path / "huge.png"
+ with open(path, "wb") as handle:
+ handle.write(_png()[:33]) # signature and IHDR, then nothing but zero bytes
+ handle.truncate(64 * 1024 * 1024)
+ started = time.monotonic()
+
+ result = await ReadTool().execute({"path": "huge.png"}, make_ctx())
+
+ assert time.monotonic() - started < 1.0
+ assert result_text(result).startswith("Read image file [image/png]\n[Image omitted: the file is 64.0MB")
diff --git a/tests/agent_core/tools/test_write_edit.py b/tests/agent_core/tools/test_write_edit.py
index b2d15cf5c..6eda3466d 100644
--- a/tests/agent_core/tools/test_write_edit.py
+++ b/tests/agent_core/tools/test_write_edit.py
@@ -7,6 +7,7 @@ import os
import random
import re
import stat
+import time
import pytest
@@ -191,6 +192,34 @@ async def test_write_and_edit_sanitize_model_text_the_same_way(tmp_path, make_ct
assert (tmp_path / "e.txt").read_bytes() == "a\ufffdb".encode()
+async def test_the_display_diff_is_bounded_by_lines_not_only_bytes(tmp_path, make_ctx):
+ """Repetitive lines made difflib quadratic (Codex measured over 22 s); the changed middle is all it sees."""
+ (tmp_path / "rep.txt").write_text("x\n" * 5000 + "target\n" + "x\n" * 5000)
+ started = time.monotonic()
+
+ result = await _edit(make_ctx, "rep.txt", {"oldText": "target", "newText": "changed"})
+
+ assert time.monotonic() - started < 2.0
+ assert not result.is_error, result_text(result)
+ # Pi pads line numbers to the widest one (five digits here).
+ assert "- 5001 target\n+ 5001 changed" in result.details["diff"]
+ assert "@@ -4997,9 +4997,9 @@" in result.details["patch"]
+
+
+async def test_a_large_changed_middle_skips_the_display_diff(tmp_path, make_ctx):
+ (tmp_path / "f.txt").write_text("".join(f"line {i}\n" for i in range(3000)))
+
+ result = await _edit(
+ make_ctx,
+ "f.txt",
+ {"oldText": "line 0\n", "newText": "first\n"},
+ {"oldText": "line 2999\n", "newText": "last\n"},
+ )
+
+ assert not result.is_error, result_text(result)
+ assert result.details == {"diff_skipped": True}
+
+
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)