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
feat(memory): admit EverOS Office attachments when LibreOffice is present (#1573)
rkrkrkk049b0a6570f4
diff --git a/Dockerfile b/Dockerfileindex 09f265bed..64d91b9bf 100644--- a/Dockerfile+++ b/Dockerfile@@ -23,6 +23,7 @@ FROM python:3.12-slim AS baseRUN apt-get update && apt-get install -y --no-install-recommends \git \tmux \+ libreoffice-nogui \&& rm -rf /var/lib/apt/lists/*WORKDIR /appdiff --git a/core/memory/attachments.py b/core/memory/attachments.pyindex 798f21d73..54309ce9b 100644--- a/core/memory/attachments.py+++ b/core/memory/attachments.py@@ -10,6 +10,7 @@ import reimport secretsimport statimport threading+import timefrom collections.abc import Collection, Sequencefrom dataclasses import dataclassfrom pathlib import Path, PurePosixPath@@ -17,6 +18,7 @@ from typing import TYPE_CHECKINGfrom urllib.parse import unquote_to_bytes, urlsplitfrom config import paths+from core.memory import modality as memory_modalityfrom core.memory.confined_filesystem import (ConfinedFilesystemError,ConfinedRoot,@@ -25,7 +27,6 @@ from core.memory.confined_filesystem import (open_confined_directory,required_no_follow_flag,)-from core.memory.modality import SUPPORTED_ATTACHMENT_EXTENSIONSfrom core.memory.types import (CaptureAttachment,MemoryContentKind,@@ -48,6 +49,7 @@ IM_ATTACHMENT_CAPTURE_PLATFORMS = frozenset(_COPY_CHUNK_BYTES = 1024 * 1024_MAX_ATTACHMENT_NAME_BYTES = 512+_OFFICE_CONVERSION_BUNDLE_BUDGET_SECONDS = 30.0_MAX_FILE_URI_BYTES = 8 * 1024_BUNDLE_ID_PATTERN = re.compile(r"[0-9a-f]{32}")_SHA256_PATTERN = re.compile(r"[0-9a-f]{64}")@@ -279,6 +281,7 @@ class AttachmentPinStore:source_root, allowed_records = self._pin_source(source_lease)with self._lock:self._verify_private_layout()+ office_conversion_deadline = _office_conversion_deadline(source_items)staging_fd = _open_private_directory(self._effective_home, self._staging, "attachment staging root")bundles_fd = _open_private_directory(self._effective_home, self._bundles, "attachment bundles root")bundle_id: str | None = None@@ -297,15 +300,16 @@ class AttachmentPinStore:pinned: list[PinnedAttachment] = []total_bytes = 0try:- for index, source in enumerate(source_items):- source_fd, source_info, source_sha256 = self._open_source(- source,- source_root=source_root,- allowed_records=allowed_records,- source_lease=source_lease,- )+ for source in source_items:+ filename = _bundle_filename(len(pinned), source.ext)+ source_fd: int | None = Nonetry:- filename = _bundle_filename(index, source.ext)+ source_fd, source_info, source_sha256 = self._open_source(+ source,+ source_root=source_root,+ allowed_records=allowed_records,+ source_lease=source_lease,+ )size_bytes, digest = _copy_source_file(source_fd,source_info,@@ -314,19 +318,59 @@ class AttachmentPinStore:total_before=total_bytes,expected_sha256=source_sha256,)+ if (+ source.ext in memory_modality.OFFICE_ATTACHMENT_EXTENSIONS+ and not _pinned_office_matches(+ stage_fd,+ filename,+ source.kind,+ source.ext,+ conversion_path=(+ self._staging / stage_name / filename+ ),+ conversion_timeout_seconds=(+ _remaining_office_conversion_seconds(+ office_conversion_deadline+ )+ ),+ )+ ):+ raise AttachmentPinError(+ "memory_invalid_input",+ "Office attachment changed before it was pinned",+ )+ except AttachmentPinError as error:+ if (+ source.ext in memory_modality.OFFICE_ATTACHMENT_EXTENSIONS+ and error.error+ in {"memory_invalid_input", "memory_input_too_large"}+ ):+ _discard_staged_file(stage_fd, filename)+ continue+ raisefinally:- os.close(source_fd)+ if source_fd is not None:+ os.close(source_fd)total_bytes += size_bytespinned.append(PinnedAttachment(kind=source.kind,name=source.name,ext=source.ext,- storage_key=_storage_key(bundle_id, index, source.ext),+ storage_key=_storage_key(+ bundle_id,+ len(pinned),+ source.ext,+ ),size_bytes=size_bytes,sha256=digest,))+ if not pinned:+ raise AttachmentPinError(+ "memory_invalid_input",+ "no attachment remained valid while pinning",+ )_fsync_fd(stage_fd, "attachment staging bundle")finally:os.close(stage_fd)@@ -408,9 +452,32 @@ class AttachmentPinStore:)try:projected: list[CaptureAttachment] = []+ office_conversion_deadline = _office_conversion_deadline(+ checked.attachments+ )for index, pinned in enumerate(checked.attachments):filename = _bundle_filename(index, pinned.ext)_verify_pinned_file(bundle_fd, filename, pinned)+ if (+ pinned.ext in memory_modality.OFFICE_ATTACHMENT_EXTENSIONS+ and not _pinned_office_matches(+ bundle_fd,+ filename,+ pinned.kind,+ pinned.ext,+ conversion_path=(+ self._bundles+ / checked.bundle_id+ / filename+ ),+ conversion_timeout_seconds=(+ _remaining_office_conversion_seconds(+ office_conversion_deadline+ )+ ),+ )+ ):+ continueprojected.append(CaptureAttachment(kind=pinned.kind,@@ -720,12 +787,25 @@ def workbench_capture_attachments(files: object) -> tuple[CaptureAttachment, ...extension = path.suffix.lstrip(".").lower()if _EXTENSION_PATTERN.fullmatch(extension) is None:continue- if extension not in SUPPORTED_ATTACHMENT_EXTENSIONS:+ if extension not in memory_modality.SUPPORTED_ATTACHMENT_EXTENSIONS:# The provider answers an unparseable extension with a permanent# rejection, so an upload it cannot read never becomes a capture.continue+ office_classification = None+ if extension in memory_modality.OFFICE_ATTACHMENT_EXTENSIONS:+ # EverOS aborts the whole /add batch when soffice is missing or the+ # bytes are not a convertible Office container.+ office_classification = memory_modality.classify_pinned_attachment(+ name,+ mimetype,+ path,+ )+ if office_classification is None:+ continuenormalized_mime = mimetype.lower().split(";", 1)[0].strip()- if normalized_mime.startswith("image/"):+ if office_classification is not None:+ kind, _classified_extension = office_classification+ elif normalized_mime.startswith("image/"):kind: MemoryContentKind = "image"elif normalized_mime.startswith("audio/"):kind = "audio"@@ -737,16 +817,7 @@ def workbench_capture_attachments(files: object) -> tuple[CaptureAttachment, ...kind = "email"else:kind = "doc"- display_name = Path(name).name- try:- encoded_name = display_name.encode("utf-8")- except UnicodeError:- continue- if len(encoded_name) > _MAX_ATTACHMENT_NAME_BYTES:- display_name = encoded_name[:_MAX_ATTACHMENT_NAME_BYTES].decode(- "utf-8",- errors="ignore",- )+ display_name = _bounded_attachment_name(Path(name).name)if display_name:converted.append(CaptureAttachment(@@ -759,6 +830,29 @@ def workbench_capture_attachments(files: object) -> tuple[CaptureAttachment, ...return tuple(converted)+def _bounded_attachment_name(name: str) -> str:+ try:+ encoded_name = name.encode("utf-8")+ except UnicodeError:+ return ""+ if len(encoded_name) <= _MAX_ATTACHMENT_NAME_BYTES:+ return name+ suffix = Path(name).suffix+ encoded_suffix = suffix.encode("utf-8", errors="ignore")+ if not suffix or len(encoded_suffix) >= _MAX_ATTACHMENT_NAME_BYTES:+ return encoded_name[:_MAX_ATTACHMENT_NAME_BYTES].decode(+ "utf-8",+ errors="ignore",+ )+ stem = name[: -len(suffix)]+ stem_budget = _MAX_ATTACHMENT_NAME_BYTES - len(encoded_suffix)+ bounded_stem = stem.encode("utf-8")[:stem_budget].decode(+ "utf-8",+ errors="ignore",+ )+ return f"{bounded_stem}{suffix}"++def _absolute_lexical(value: Path | str) -> Path:return Path(os.path.abspath(os.path.expanduser(os.fspath(value))))@@ -970,6 +1064,70 @@ def _require_safe_source_file(info: os.stat_result) -> None:_require_current_owner(info, "attachment source", storage=False)+def _office_conversion_deadline(+ attachments: Sequence[CaptureAttachment] | tuple[PinnedAttachment, ...],+) -> float | None:+ if not any(+ attachment.ext in memory_modality.OFFICE_ATTACHMENT_EXTENSIONS+ for attachment in attachments+ ):+ return None+ return time.monotonic() + _OFFICE_CONVERSION_BUNDLE_BUDGET_SECONDS+++def _remaining_office_conversion_seconds(deadline: float | None) -> float | None:+ if deadline is None:+ return None+ return max(0.0, deadline - time.monotonic())+++def _pinned_office_matches(+ directory_fd: int,+ filename: str,+ kind: MemoryContentKind,+ extension: str,+ *,+ conversion_path: Path | None = None,+ conversion_timeout_seconds: float | None = None,+) -> bool:+ try:+ descriptor = os.open(filename, _file_read_flags(), dir_fd=directory_fd)+ except OSError as error:+ raise _storage_failure(error, "pinned Office attachment is unavailable") from error+ try:+ _require_private_file(os.fstat(descriptor), "pinned Office attachment")+ classification = memory_modality.classify_pinned_attachment(+ filename,+ "application/octet-stream",+ Path(filename),+ file_fd=descriptor,+ )+ if classification != (kind, extension):+ return False+ if conversion_path is None:+ return True+ if (+ conversion_timeout_seconds is None+ or conversion_timeout_seconds <= 0+ ):+ return False+ return memory_modality.office_document_conversion_succeeds(+ conversion_path,+ timeout_seconds=conversion_timeout_seconds,+ )+ finally:+ os.close(descriptor)+++def _discard_staged_file(directory_fd: int, filename: str) -> None:+ try:+ os.unlink(filename, dir_fd=directory_fd)+ except FileNotFoundError:+ return+ except OSError as error:+ raise _storage_failure(error, "invalid Office attachment could not be discarded") from error++def _copy_source_file(source_fd: int,source_info: os.stat_result,@@ -1193,7 +1351,7 @@ def _valid_kind_name_extension(kind: object, name: object, extension: object) ->or "\x00" in nameor not isinstance(extension, str)or _EXTENSION_PATTERN.fullmatch(extension) is None- or extension not in SUPPORTED_ATTACHMENT_EXTENSIONS+ or extension not in memory_modality.SUPPORTED_ATTACHMENT_EXTENSIONS):return Falsetry:@@ -1266,7 +1424,7 @@ def _validate_private_bundle(parent_fd: int, name: str) -> tuple[str, ...]:if (match is Noneor match.group(1) != f"{index:02d}"- or match.group(2) not in SUPPORTED_ATTACHMENT_EXTENSIONS+ or match.group(2) not in memory_modality.SUPPORTED_ATTACHMENT_EXTENSIONS):raise AttachmentBundleInvalidError("memory_store_unavailable",diff --git a/core/memory/coordinator.py b/core/memory/coordinator.pyindex 7b8584dcb..d6c9063c8 100644--- a/core/memory/coordinator.py+++ b/core/memory/coordinator.py@@ -552,6 +552,20 @@ class SessionFlushCoordinator:retryable=True,)return False+ if (+ row.attachment_bundle_id is not None+ and not row.payload_text.strip()+ and not attachments+ ):+ await self._settle_failure(+ row,+ lease_owner=lease_owner,+ outcome=MessageFailure(+ error="memory_invalid_input",+ retryable=False,+ ),+ )+ return Falsecapture = ProviderCapture(session_ref=row.provider_session_ref,text=row.payload_text,diff --git a/core/memory/modality.py b/core/memory/modality.pyindex d87e82231..c3ae89d93 100644--- a/core/memory/modality.py+++ b/core/memory/modality.py@@ -7,11 +7,16 @@ amount of retrying can clear, so the capture boundary filters uploads hereinstead of discovering the limit at the provider.This mirrors ``everalgo.types.modality`` in the packaged EverOS runtime-runtime and must stay in sync with it. Two modality groups from that table are-deliberately excluded because the text-only build lacks their integrations:+and must stay in sync with it. Two upstream groups stay out of the live+allowlist for host-capability reasons:-- ``DOCUMENT`` (docx / xlsx / pptx / ODF / iWork / rtf) needs LibreOffice-- ``svg`` needs the cairosvg integration+- ``svg`` needs the cairosvg integration, which this runtime does not ship+- video is still unimplemented in the pinned EverOS parser++Office / iWork / ODF / RTF are admitted only when the host can resolve+LibreOffice's ``soffice`` binary. EverOS converts those files to PDF before+the multimodal LLM sees them; sending one without ``soffice`` aborts the+whole ``/add`` batch with ``CAPABILITY_UNAVAILABLE``.Kept dependency-light on purpose: ``core.memory.sidecar`` imports this from theruntime child process, which runs with a minimal environment.@@ -21,11 +26,38 @@ from __future__ import annotationsimport codecsimport os+import shutil+import stat+import struct+import subprocess+import tempfile+import zipfilefrom pathlib import Pathfrom core.memory.types import MemoryContentKind+# EverOS's macOS fallback; keep this identical so Avibe and the parser agree.+_MACOS_SOFFICE = Path("/Applications/LibreOffice.app/Contents/MacOS/soffice")++OFFICE_ATTACHMENT_EXTENSIONS: frozenset[str] = frozenset(+ {+ "docx",+ "pptx",+ "xlsx",+ "doc",+ "ppt",+ "xls",+ "pages",+ "key",+ "numbers",+ "odt",+ "ods",+ "odp",+ "rtf",+ }+)+SUPPORTED_ATTACHMENT_EXTENSIONS: frozenset[str] = frozenset({# DIRECT: plain text, parsed without any model call@@ -58,33 +90,163 @@ SUPPORTED_ATTACHMENT_EXTENSIONS: frozenset[str] = frozenset("htm","eml",+ *OFFICE_ATTACHMENT_EXTENSIONS,})# These pinned upstream formats need unavailable local integrations. They are# deliberately a static Avibe policy, not a provider import in request handling.-PINNED_UPSTREAM_EXCLUDED_EXTENSIONS: frozenset[str] = frozenset(- {- "svg",- "docx",- "pptx",- "xlsx",- "doc",- "ppt",- "xls",- "pages",- "key",- "numbers",- "odt",- "ods",- "odp",- "rtf",- }-)+PINNED_UPSTREAM_EXCLUDED_EXTENSIONS: frozenset[str] = frozenset({"svg"})_IMAGE_EXTENSIONS = frozenset({"png", "jpg", "jpeg", "webp", "tiff", "tif", "bmp"})_AUDIO_EXTENSIONS = frozenset({"mp3", "wav", "m4a", "amr", "aiff", "aac", "ogg", "flac"})_TEXT_EXTENSIONS = frozenset({"txt", "md", "vtt", "csv", "tsv"})+_OFFICE_ZIP_MARKERS: dict[str, frozenset[str]] = {+ "docx": frozenset({"[Content_Types].xml", "word/document.xml"}),+ "pptx": frozenset({"[Content_Types].xml", "ppt/presentation.xml"}),+ "xlsx": frozenset({"[Content_Types].xml", "xl/workbook.xml"}),+ "odt": frozenset({"mimetype", "content.xml"}),+ "ods": frozenset({"mimetype", "content.xml"}),+ "odp": frozenset({"mimetype", "content.xml"}),+ # Current iWork packages share the IWA document index; the extension tells+ # LibreOffice which filter to apply.+ "pages": frozenset({"Index/Document.iwa"}),+ "key": frozenset({"Index/Document.iwa"}),+ "numbers": frozenset({"Index/Document.iwa"}),+}+_OFFICE_OLE_EXTENSIONS = frozenset({"doc", "ppt", "xls"})+_OFFICE_OLE_REQUIRED_STREAM_GROUPS: dict[str, tuple[frozenset[str], ...]] = {+ "doc": (+ frozenset({"WordDocument"}),+ frozenset({"0Table", "1Table"}),+ ),+ "ppt": (frozenset({"PowerPoint Document"}),),+ "xls": (frozenset({"Book", "Workbook"}),),+}+_OFFICE_RTF_EXTENSIONS = frozenset({"rtf"})+_OFFICE_MIMES_BY_EXTENSION: dict[str, frozenset[str]] = {+ "docx": frozenset(+ {"application/vnd.openxmlformats-officedocument.wordprocessingml.document"}+ ),+ "pptx": frozenset(+ {"application/vnd.openxmlformats-officedocument.presentationml.presentation"}+ ),+ "xlsx": frozenset(+ {"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}+ ),+ "doc": frozenset({"application/msword"}),+ "ppt": frozenset({"application/vnd.ms-powerpoint"}),+ "xls": frozenset({"application/vnd.ms-excel"}),+ "pages": frozenset(+ {+ "application/vnd.apple.pages",+ "application/x-iwork-pages-sffpages",+ }+ ),+ "key": frozenset(+ {+ "application/vnd.apple.keynote",+ "application/x-iwork-keynote-sffkey",+ }+ ),+ "numbers": frozenset(+ {+ "application/vnd.apple.numbers",+ "application/x-iwork-numbers-sffnumbers",+ }+ ),+ "odt": frozenset({"application/vnd.oasis.opendocument.text"}),+ "ods": frozenset({"application/vnd.oasis.opendocument.spreadsheet"}),+ "odp": frozenset({"application/vnd.oasis.opendocument.presentation"}),+ "rtf": frozenset({"application/rtf", "text/rtf"}),+}+_ODF_MIME_BY_EXTENSION = {+ "odt": "application/vnd.oasis.opendocument.text",+ "ods": "application/vnd.oasis.opendocument.spreadsheet",+ "odp": "application/vnd.oasis.opendocument.presentation",+}+_OLE_MAGIC = b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1"+_RTF_MAGIC = b"{\\rtf"+_ZIP_EOCD = struct.Struct("<4s4H2LH")+_ZIP_EOCD_SIGNATURE = b"PK\x05\x06"+_ZIP_CENTRAL_DIRECTORY_SIGNATURE = b"PK\x01\x02"+_ZIP_CENTRAL_DIRECTORY_HEADER_BYTES = 46+_MAX_ZIP_COMMENT_BYTES = 65_535+_MAX_OFFICE_ZIP_ENTRIES = 4_096+_MAX_OFFICE_ZIP_MEMBER_BYTES = 32 * 1024 * 1024+_MAX_OFFICE_ZIP_TOTAL_UNCOMPRESSED_BYTES = 100 * 1024 * 1024+_OFFICE_CONVERSION_TIMEOUT_SECONDS = 30+++def _office_converter_path() -> Path | None:+ resolved = shutil.which("soffice", path="/usr/bin:/bin")+ if resolved is not None:+ return Path(resolved)+ if _MACOS_SOFFICE.is_file() and os.access(_MACOS_SOFFICE, os.X_OK):+ return _MACOS_SOFFICE+ return None+++def office_conversion_available() -> bool:+ """Return whether the Memory sidecar can resolve LibreOffice.++ The sidecar PATH is ``<runtime>/bin:/usr/bin:/bin``. Probe only those+ locations plus EverOS's macOS App fallback so Avibe never admits an+ Office file the parser child cannot convert.+ """++ return _office_converter_path() is not None+++def office_document_conversion_succeeds(+ path: Path,+ *,+ timeout_seconds: float = _OFFICE_CONVERSION_TIMEOUT_SECONDS,+) -> bool:+ """Prove that the sidecar-visible converter accepts one private staged file."""++ converter = _office_converter_path()+ bounded_timeout = min(+ float(_OFFICE_CONVERSION_TIMEOUT_SECONDS),+ max(0.0, float(timeout_seconds)),+ )+ if converter is None or bounded_timeout <= 0:+ return False+ try:+ with tempfile.TemporaryDirectory(prefix="avibe-office-preflight-") as temp_dir:+ temp_root = Path(temp_dir)+ output_dir = temp_root / "output"+ profile_dir = temp_root / "profile"+ output_dir.mkdir(mode=0o700)+ profile_dir.mkdir(mode=0o700)+ result = subprocess.run(+ [+ str(converter),+ "--headless",+ f"-env:UserInstallation={profile_dir.as_uri()}",+ "--convert-to",+ "pdf",+ "--outdir",+ str(output_dir),+ str(path),+ ],+ cwd=temp_root,+ env={"HOME": str(temp_root), "PATH": "/usr/bin:/bin"},+ stdin=subprocess.DEVNULL,+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ timeout=bounded_timeout,+ check=False,+ )+ output = output_dir / f"{path.stem}.pdf"+ output_info = output.lstat()+ return (+ result.returncode == 0+ and stat.S_ISREG(output_info.st_mode)+ and output_info.st_size > 0+ )+ except (OSError, subprocess.TimeoutExpired):+ return Falsedef classify_pinned_attachment(@@ -134,6 +296,20 @@ def classify_pinned_attachment(}:return Nonereturn "pdf", extension+ if extension in OFFICE_ATTACHMENT_EXTENSIONS:+ if not office_conversion_available() or not _office_container_matches(+ extension,+ path,+ file_fd,+ sample,+ ):+ return None+ if (+ normalized_mime != "application/octet-stream"+ and normalized_mime not in _OFFICE_MIMES_BY_EXTENSION[extension]+ ):+ return None+ return "doc", extensionif not _valid_utf8_text_file(path, file_fd):return Noneif normalized_mime != "application/octet-stream" and not (@@ -176,6 +352,174 @@ def _extension_aliases_match(expected: str, detected: str) -> bool:return expected == detected or any({expected, detected} <= group for group in aliases)+def _office_container_matches(+ extension: str,+ path: Path,+ file_fd: int | None,+ sample: bytes,+) -> bool:+ if extension in _OFFICE_ZIP_MARKERS:+ return _office_zip_matches(extension, path, file_fd)+ if extension in _OFFICE_OLE_EXTENSIONS:+ return _office_ole_matches(extension, path, file_fd, sample)+ if extension in _OFFICE_RTF_EXTENSIONS:+ return sample.startswith(_RTF_MAGIC)+ return False+++def _office_ole_matches(+ extension: str,+ path: Path,+ file_fd: int | None,+ sample: bytes,+) -> bool:+ if not sample.startswith(_OLE_MAGIC):+ return False+ try:+ import olefile++ with _open_attachment_file(path, file_fd) as file_obj:+ file_obj.seek(0)+ with olefile.OleFileIO(+ file_obj,+ raise_defects=olefile.DEFECT_INCORRECT,+ ) as archive:+ return all(+ any(+ archive.exists(stream_name)+ and archive.get_size(stream_name) > 0+ for stream_name in alternatives+ )+ for alternatives in _OFFICE_OLE_REQUIRED_STREAM_GROUPS[extension]+ )+ except Exception:+ return False+++def _office_zip_matches(extension: str, path: Path, file_fd: int | None) -> bool:+ try:+ with _open_attachment_file(path, file_fd) as file_obj:+ if not _office_zip_entry_count_bounded(file_obj):+ return False+ file_obj.seek(0)+ with zipfile.ZipFile(file_obj) as archive:+ names = archive.namelist()+ if len(names) != len(set(names)):+ return False+ total_uncompressed = 0+ for info in archive.infolist():+ if (+ info.file_size < 0+ or info.file_size > _MAX_OFFICE_ZIP_MEMBER_BYTES+ ):+ return False+ total_uncompressed += info.file_size+ if total_uncompressed > _MAX_OFFICE_ZIP_TOTAL_UNCOMPRESSED_BYTES:+ return False+ if not _OFFICE_ZIP_MARKERS[extension].issubset(names):+ return False+ expected_mime = _ODF_MIME_BY_EXTENSION.get(extension)+ if expected_mime is None:+ return True+ mime_info = archive.getinfo("mimetype")+ if mime_info.file_size > 128:+ return False+ return archive.read(mime_info) == expected_mime.encode("ascii")+ except (+ KeyError,+ NotImplementedError,+ OSError,+ RuntimeError,+ ValueError,+ zipfile.BadZipFile,+ zipfile.LargeZipFile,+ ):+ return False+++def _office_zip_entry_count_bounded(file_obj) -> bool:+ file_obj.seek(0, os.SEEK_END)+ archive_size = file_obj.tell()+ tail_size = min(archive_size, _ZIP_EOCD.size + _MAX_ZIP_COMMENT_BYTES)+ if tail_size < _ZIP_EOCD.size:+ return False+ file_obj.seek(-tail_size, os.SEEK_END)+ tail = file_obj.read(tail_size)+ eocd_offset = tail.rfind(_ZIP_EOCD_SIGNATURE)+ if eocd_offset < 0:+ return False+ try:+ (+ signature,+ disk_number,+ central_directory_disk,+ entries_on_disk,+ total_entries,+ central_directory_size,+ central_directory_offset,+ comment_size,+ ) = _ZIP_EOCD.unpack_from(tail, eocd_offset)+ except struct.error:+ return False+ eocd_absolute_offset = archive_size - tail_size + eocd_offset+ if not (+ signature == _ZIP_EOCD_SIGNATURE+ and eocd_offset + _ZIP_EOCD.size + comment_size == len(tail)+ and disk_number == central_directory_disk == 0+ and entries_on_disk == total_entries+ and 0 < total_entries <= _MAX_OFFICE_ZIP_ENTRIES+ and total_entries != 0xFFFF+ and central_directory_size != 0xFFFFFFFF+ and central_directory_offset != 0xFFFFFFFF+ and central_directory_offset + central_directory_size+ <= eocd_absolute_offset+ ):+ return False+ return _office_zip_central_directory_matches(+ file_obj,+ eocd_absolute_offset=eocd_absolute_offset,+ central_directory_size=central_directory_size,+ expected_entries=total_entries,+ )+++def _office_zip_central_directory_matches(+ file_obj,+ *,+ eocd_absolute_offset: int,+ central_directory_size: int,+ expected_entries: int,+) -> bool:+ central_directory_start = eocd_absolute_offset - central_directory_size+ if central_directory_start < 0:+ return False+ file_obj.seek(central_directory_start)+ consumed = 0+ observed_entries = 0+ while consumed < central_directory_size:+ header = file_obj.read(_ZIP_CENTRAL_DIRECTORY_HEADER_BYTES)+ if (+ len(header) != _ZIP_CENTRAL_DIRECTORY_HEADER_BYTES+ or not header.startswith(_ZIP_CENTRAL_DIRECTORY_SIGNATURE)+ ):+ return False+ filename_size, extra_size, comment_size = struct.unpack_from("<3H", header, 28)+ variable_size = filename_size + extra_size + comment_size+ entry_size = _ZIP_CENTRAL_DIRECTORY_HEADER_BYTES + variable_size+ consumed += entry_size+ observed_entries += 1+ if (+ consumed > central_directory_size+ or observed_entries > _MAX_OFFICE_ZIP_ENTRIES+ ):+ return False+ file_obj.seek(variable_size, os.SEEK_CUR)+ return (+ consumed == central_directory_size+ and observed_entries == expected_entries+ )++def _image_extension(data: bytes) -> str | None:if data.startswith(b"\x89PNG\r\n\x1a\n"):return "png"diff --git a/docs/MEMORY.md b/docs/MEMORY.mdindex a66973af4..8321fcb35 100644--- a/docs/MEMORY.md+++ b/docs/MEMORY.md@@ -25,8 +25,12 @@ Only direct, ordinary files shared by a human are eligible. Bot, system,forwarded, edited, quoted, rich, and unrecognized native message shapes areexcluded. Avibe then validates each eligible file against one shared format andcontent policy. Supported formats are plain text, Markdown, CSV/TSV, VTT, PDF,-bitmap images, audio, HTML, and EML. Unsupported or malformed files are skipped-independently, so eligible text and valid siblings can still be captured.+bitmap images, audio, HTML, EML, and Office / iWork / ODF / RTF documents when+LibreOffice is installed. Native Windows currently skips these Office formats;+Linux and macOS hosts can enable them with a sidecar-visible LibreOffice install.+SVG and video stay excluded. Unsupported or malformed+files are skipped independently, so eligible text and valid siblings can still+be captured.Each turn is limited to 8 captured attachments, 25 MiB per attachment, and100 MiB in total. Admitted files are copied into private Avibe storage until thediff --git a/docs/MEMORY_ZH.md b/docs/MEMORY_ZH.mdindex 83fec425f..b63a2bd9a 100644--- a/docs/MEMORY_ZH.md+++ b/docs/MEMORY_ZH.md@@ -11,7 +11,9 @@ Avibe 记忆会把符合条件的 Workbench 和私聊消息提炼为按用户隔只有人类直接分享的普通文件才符合条件。机器人、系统、转发、编辑、引用、富内容和无法识别的原生消息形状都会被排除。随后,Avibe 使用同一套格式与内容策略检查每个符合条件-的文件。支持纯文本、Markdown、CSV/TSV、VTT、PDF、位图图片、音频、HTML 和 EML。+的文件。支持纯文本、Markdown、CSV/TSV、VTT、PDF、位图图片、音频、HTML、EML,以及在已安装+LibreOffice 时的 Office / iWork / ODF / RTF 文档。原生 Windows 当前会跳过这些 Office+格式;Linux 与 macOS 可通过 Memory 子进程能够访问的 LibreOffice 安装来启用。SVG 和视频仍不支持。不支持或格式异常的文件会被单独跳过,符合条件的文本和其它有效附件仍可进入捕获。每轮最多捕获 8 个附件,单个附件最大 25 MiB,总计最大 100 MiB。通过准入的文件会复制diff --git a/docs/plans/memory-im-attachments-1425.md b/docs/plans/memory-im-attachments-1425.mdindex 6f6a1dea3..3aba82e75 100644--- a/docs/plans/memory-im-attachments-1425.md+++ b/docs/plans/memory-im-attachments-1425.md@@ -27,10 +27,10 @@ redaction, and capture behavior.rejects the turn. If a selected attachment later fails descriptor/hashverification during durable pinning, the same capture is retried once astext-only; an attachment-only turn retains the closed pin failure.-- The first release keeps the existing Avibe allowlist in- `core/memory/modality.py`: bitmap images, PDF, supported audio, direct text,- CSV, VTT, HTML, and EML. Office/iWork/ODF/RTF, SVG, and video remain excluded- even where EverOS can parse them.+- The live allowlist in `core/memory/modality.py` follows the pinned EverOS+ parser except for SVG and video. Office/iWork/ODF/RTF files are admitted only+ when the host can resolve LibreOffice `soffice`; otherwise they are skipped+ per file so a missing converter cannot abort the rest of the `/add` batch.- The Memory consumer alone applies the limit of 8 files, 25 MiB per file, and100 MiB per bundle. Ordinary Agent attachment behavior is unchanged.- Multimodal preflight sends a tiny generated image containing no user ordiff --git a/docs/regression/memory-im-attachment-five-platform-acceptance.md b/docs/regression/memory-im-attachment-five-platform-acceptance.mdindex cf959e4fe..e6dcdc6f6 100644--- a/docs/regression/memory-im-attachment-five-platform-acceptance.md+++ b/docs/regression/memory-im-attachment-five-platform-acceptance.md@@ -280,9 +280,10 @@ Decision:forwards, or snapshots.- Claiming WeChat bot/self/system exclusion before the raw shapes prove a stablediscriminator. This checklist exercises only the ordinary human baseline.-- Capturing SVG, Office/iWork/ODF/RTF documents, or other extensions excluded by- `core/memory/modality.py::SUPPORTED_ATTACHMENT_EXTENSIONS`. WeChat video may- reach shared admission, but video processing is not enabled by this acceptance.+- Capturing SVG or video. Office/iWork/ODF/RTF documents are in the live+ allowlist only when the regression host has LibreOffice; this checklist still+ uses SVG as the rejected sibling. WeChat video may reach shared admission, but+ video processing is not enabled by this acceptance.- Group/channel, unbound, edited, forwarded, webhook, or system-message Memorycapture, and bot-authored capture on platforms with verified source facts.Quoted/replied-to traffic is unverified and out of scope rather than claimeddiff --git a/install.ps1 b/install.ps1index 009534c9d..0dc86654b 100644--- a/install.ps1+++ b/install.ps1@@ -134,6 +134,10 @@ function Install-Node {throw "Node.js $NODE_MINIMUM_REQUIREMENT is required for Show Pages runtime. Please install Node.js LTS from https://nodejs.org/ if needed."}+function Warn-IfLibreOfficeMissing {+ Write-Warning "Memory Office attachment capture is unavailable on native Windows. LibreOffice installed on Windows is not used by the managed Memory runtime."+}+function Install-NodeOptional {try {Install-Node@@ -412,6 +416,7 @@ function Main {# Node.js only powers the optional managed Show Page runtime. Never let it# block installation of the main avibe CLI/service.Install-NodeOptional+ Warn-IfLibreOfficeMissing# Install avibe-osInstall-Vibediff --git a/install.sh b/install.shindex 43b66caa2..ee63ef3dc 100755--- a/install.sh+++ b/install.sh@@ -376,6 +376,17 @@ install_node() {return 1}+warn_if_libreoffice_missing() {+ if PATH="/usr/bin:/bin" command -v soffice >/dev/null 2>&1 || [ -x /Applications/LibreOffice.app/Contents/MacOS/soffice ]; then+ success "LibreOffice is available for Memory Office attachment capture"+ return 0+ fi++ warn "LibreOffice is not available, so Memory will skip Word, Excel, PowerPoint, and other Office attachments."+ warn "Install it to enable that path: macOS \"brew install --cask libreoffice\", Debian/Ubuntu \"apt-get install -y libreoffice-nogui\"."+ return 0+}+install_node_optional() {set +einstall_node@@ -706,6 +717,10 @@ main() {# Node.js only powers the optional managed Show Page runtime. Never let it# block installation of the main avibe CLI/service.install_node_optional++ # LibreOffice only powers Memory Office capture. Warn when it is missing;+ # never block the main avibe CLI/service or download a host package here.+ warn_if_libreoffice_missing# Install avibe-osinstall_vibediff --git a/pyproject.toml b/pyproject.tomlindex b7a480676..9a09e7d91 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -69,6 +69,7 @@ dependencies = ["packaging>=23.0","uvicorn[standard]>=0.27","imagesize>=1.4.1",+ "olefile>=0.47","pywebpush>=2.0.3","cryptography>=42.0",# keccak256 + ripemd160 for vault signing-key address derivationdiff --git a/scripts/incus_regression.py b/scripts/incus_regression.pyindex 45c42d2ea..78eb0a2ea 100644--- a/scripts/incus_regression.py+++ b/scripts/incus_regression.py@@ -598,6 +598,7 @@ def cloud_init_user_data() -> str:" - python3-venv"," - rsync"," - sudo",+ " - libreoffice-nogui","users:",f" - name: {SERVICE_USER}"," groups: sudo",@@ -649,6 +650,26 @@ def ensure_proxy_device(runner: Runner, target: RegressionTarget, *, remote: strrunner.run(incus(*proxy_device_args(target, remote=remote), project=target.project))+def ensure_office_converter(+ runner: Runner,+ target: RegressionTarget,+ *,+ remote: str | None,+) -> None:+ runner.run(+ root_exec(+ target,+ "set -euo pipefail; "+ "if ! PATH=/usr/bin:/bin command -v soffice >/dev/null 2>&1; then "+ "export DEBIAN_FRONTEND=noninteractive; "+ "apt-get update; "+ "apt-get install -y --no-install-recommends libreoffice-nogui; "+ "fi",+ remote=remote,+ )+ )++def ensure_project_and_instance(runner: Runner,target: RegressionTarget,@@ -699,6 +720,7 @@ def ensure_project_and_instance(remote=remote,))+ ensure_office_converter(runner, target, remote=remote)runner.run(root_exec(target,@@ -1394,7 +1416,7 @@ def cmd_build_base(args: argparse.Namespace) -> int:"""\set -euo pipefailapt-get update- apt-get install -y bash ca-certificates curl git build-essential python3 python3-pip python3-venv rsync sudo tmux+ apt-get install -y bash ca-certificates curl git build-essential python3 python3-pip python3-venv rsync sudo tmux libreoffice-noguicurl -fsSL https://deb.nodesource.com/setup_20.x | bash -apt-get install -y nodejs# Install the agent backends under the service user's home so thediff --git a/tests/scenarios/memory_im_attachment_capture/catalog.yaml b/tests/scenarios/memory_im_attachment_capture/catalog.yamlindex 5d6befc99..b24301edc 100644--- a/tests/scenarios/memory_im_attachment_capture/catalog.yaml+++ b/tests/scenarios/memory_im_attachment_capture/catalog.yaml@@ -13,7 +13,7 @@ contract:admission: bound_enabled_one_to_one_dm_fail_closedopt_in: explicit_complete_multimodal_endpointdegradation: text_and_valid_attachments_survive_independently- formats: current_avibe_memory_allowlist+ formats: everos_parser_minus_svg_video_office_requires_live_sofficelimits: memory_only_8_files_25_mib_each_100_mib_bundlepreflight: generated_image_without_user_dataworkbench_compatibility: implicit_main_llm_for_one_cycle@@ -97,3 +97,10 @@ scenarios:layer: scenariodelivery_slice: 7test: tests/scenarios/memory_im_attachment_capture/test_memory_im_attachment_capture_scenarios.py::test_provider_attachment_rejection_retries_caption_as_text_only+ - id: MEMORY-IM-ATTACH-012+ name: Office attachments require LibreOffice at admission and delivery+ status: covered+ kind: boundary+ layer: scenario+ delivery_slice: 8+ test: tests/scenarios/memory_im_attachment_capture/test_memory_im_attachment_capture_scenarios.py::test_office_attachment_requires_soffice_and_preserves_valid_siblingsdiff --git a/tests/scenarios/memory_im_attachment_capture/observations.yaml b/tests/scenarios/memory_im_attachment_capture/observations.yamlindex 8ed030a0d..2bb6ca035 100644--- a/tests/scenarios/memory_im_attachment_capture/observations.yaml+++ b/tests/scenarios/memory_im_attachment_capture/observations.yaml@@ -33,3 +33,14 @@ observations:fail-closed for embed-bearing messages pending the Incus matrix.evidence:avibe_commit: 063aebd29713615e63ec828da94c4c8b339b6647+ - id: MEMORY-IM-ATTACH-OBS-005+ scenarios:+ - MEMORY-IM-ATTACH-012+ observation: >-+ EverOS converts Office/iWork/ODF/RTF through LibreOffice before the+ multimodal LLM; a missing soffice binary returns CAPABILITY_UNAVAILABLE+ for the whole /add batch. Avibe therefore admits those extensions only+ when soffice is resolvable, rechecks before delivery, and skips affected+ documents independently otherwise.+ evidence:+ everos_commit: 560fb80b59fe5f033a911e38bebc87a3232a5234diff --git a/tests/scenarios/memory_im_attachment_capture/test_memory_im_attachment_capture_catalog.py b/tests/scenarios/memory_im_attachment_capture/test_memory_im_attachment_capture_catalog.pyindex fb4ce6129..a9654a1e6 100644--- a/tests/scenarios/memory_im_attachment_capture/test_memory_im_attachment_capture_catalog.py+++ b/tests/scenarios/memory_im_attachment_capture/test_memory_im_attachment_capture_catalog.py@@ -13,7 +13,7 @@ LOCKED_CONTRACT = {"admission": "bound_enabled_one_to_one_dm_fail_closed","opt_in": "explicit_complete_multimodal_endpoint","degradation": "text_and_valid_attachments_survive_independently",- "formats": "current_avibe_memory_allowlist",+ "formats": "everos_parser_minus_svg_video_office_requires_live_soffice","limits": "memory_only_8_files_25_mib_each_100_mib_bundle","preflight": "generated_image_without_user_data","workbench_compatibility": "implicit_main_llm_for_one_cycle",@@ -68,6 +68,7 @@ def test_memory_im_attachment_catalog_is_indexed_and_locks_the_approved_contract("MEMORY-IM-ATTACH-009", "degradation", 6),("MEMORY-IM-ATTACH-010", "boundary", 4),("MEMORY-IM-ATTACH-011", "degradation", 7),+ ("MEMORY-IM-ATTACH-012", "boundary", 8),],)def test_memory_im_attachment_covered_scenario_contract(@@ -93,6 +94,7 @@ def test_memory_im_attachment_covered_scenario_contract("MEMORY-IM-ATTACH-009","MEMORY-IM-ATTACH-010","MEMORY-IM-ATTACH-011",+ "MEMORY-IM-ATTACH-012",}assert rows[scenario_id]["status"] == "covered"assert rows[scenario_id]["kind"] == kinddiff --git a/tests/scenarios/memory_im_attachment_capture/test_memory_im_attachment_capture_scenarios.py b/tests/scenarios/memory_im_attachment_capture/test_memory_im_attachment_capture_scenarios.pyindex 38e449048..36cf4ef72 100644--- a/tests/scenarios/memory_im_attachment_capture/test_memory_im_attachment_capture_scenarios.py+++ b/tests/scenarios/memory_im_attachment_capture/test_memory_im_attachment_capture_scenarios.py@@ -4,7 +4,9 @@ from __future__ import annotationsimport asyncioimport base64+import ioimport json+import zipfilefrom types import SimpleNamespaceimport pytest@@ -29,6 +31,14 @@ from tests.scenario_harness.memory_im_attachments import (from vibe import cli, internal_client+def _xlsx_bytes() -> bytes:+ payload = io.BytesIO()+ with zipfile.ZipFile(payload, "w") as archive:+ archive.writestr("[Content_Types].xml", b"content types")+ archive.writestr("xl/workbook.xml", b"workbook")+ return payload.getvalue()++def test_bound_slack_dm_attachment_reaches_search_with_redacted_call_log(tmp_path,monkeypatch,@@ -314,6 +324,92 @@ def test_provider_attachment_rejection_retries_caption_as_text_only(assert harness.memory_bundle_entries == ()+def test_office_attachment_requires_soffice_and_preserves_valid_siblings(+ tmp_path,+ monkeypatch,+) -> None:+ """Scenario: MEMORY-IM-ATTACH-012."""++ monkeypatch.setattr(+ "core.memory.modality.office_document_conversion_succeeds",+ lambda _path, **_kwargs: True,+ )+ monkeypatch.setattr("core.memory.modality.office_conversion_available", lambda: False)+ without_home = tmp_path / "without-soffice"+ monkeypatch.setenv("AVIBE_HOME", str(without_home / "avibe-home"))+ without_soffice = MemoryIMAttachmentScenarioHarness(without_home)+ asyncio.run(+ without_soffice.capture(+ text="Keep the image when Office conversion is missing",+ payloads={+ "valid.png": ("image/png", PNG_BYTES),+ "report.xlsx": (+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",+ _xlsx_bytes(),+ ),+ },+ )+ )++ assert [item.name for item in without_soffice.provider.captures[0].attachments] == [+ "valid.png"+ ]++ monkeypatch.setattr("core.memory.modality.office_conversion_available", lambda: True)+ with_home = tmp_path / "with-soffice"+ monkeypatch.setenv("AVIBE_HOME", str(with_home / "avibe-home"))+ with_soffice = MemoryIMAttachmentScenarioHarness(with_home)+ asyncio.run(+ with_soffice.capture(+ text="Capture the spreadsheet when Office conversion is present",+ payloads={+ "valid.png": ("image/png", PNG_BYTES),+ "report.xlsx": (+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",+ _xlsx_bytes(),+ ),+ },+ )+ )++ assert [item.name for item in with_soffice.provider.captures[0].attachments] == [+ "valid.png",+ "report.xlsx",+ ]+ assert [item.kind for item in with_soffice.provider.captures[0].attachments] == [+ "image",+ "doc",+ ]+ assert with_soffice.memory_bundle_entries == ()++ availability = [True, False]+ monkeypatch.setattr(+ "core.memory.modality.office_conversion_available",+ lambda: availability.pop(0),+ )+ stale_home = tmp_path / "soffice-removed-before-delivery"+ monkeypatch.setenv("AVIBE_HOME", str(stale_home / "avibe-home"))+ stale_soffice = MemoryIMAttachmentScenarioHarness(stale_home)+ asyncio.run(+ stale_soffice.capture(+ text="Keep the image after Office conversion disappears",+ payloads={+ "valid.png": ("image/png", PNG_BYTES),+ "report.xlsx": (+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",+ _xlsx_bytes(),+ ),+ },+ )+ )++ assert availability == []+ assert [item.name for item in stale_soffice.provider.captures[0].attachments] == [+ "valid.png"+ ]+ assert stale_soffice.memory_bundle_entries == ()++class _ScenarioPrincipals:def principal_for_user_key(self, user_key: str) -> str:assert user_key.split(":", 1)[0] in {"discord", "telegram", "lark", "wechat"}diff --git a/tests/test_incus_regression.py b/tests/test_incus_regression.pyindex d8b7ec6fc..9ea0239fe 100644--- a/tests/test_incus_regression.py+++ b/tests/test_incus_regression.py@@ -287,6 +287,7 @@ def test_cloud_init_configures_systemd_service_without_source_code() -> None:assert "MemoryAccounting=yes" in dataassert "/opt/avibe/source" in dataassert "/home/avibe/.vibe_remote" in data+ assert "libreoffice-nogui" in datadef test_project_config_marks_regression_target() -> None:@@ -487,6 +488,12 @@ def test_existing_instance_proxy_device_is_refreshed() -> None:rendered = [" ".join(command) for command, _ in commands]assert "incus --project avr-master config device remove avibe-master ui" in renderedassert any("incus --project avr-master config device add avibe-master ui proxy listen=tcp:127.0.0.1:15131" in command for command in rendered)+ assert not any(" init " in f" {command} " for command in rendered)+ assert any(+ "PATH=/usr/bin:/bin command -v soffice" in command+ and "apt-get install -y --no-install-recommends libreoffice-nogui" in command+ for command in rendered+ )def test_build_base_uses_publishable_temp_instance() -> None:diff --git a/tests/test_install_script.py b/tests/test_install_script.pyindex 4c04284d8..140d17ec3 100644--- a/tests/test_install_script.py+++ b/tests/test_install_script.py@@ -9,6 +9,7 @@ from pathlib import PathREPO_ROOT = Path(__file__).resolve().parents[1]INSTALL_SCRIPT = REPO_ROOT / "install.sh"+INSTALL_POWERSHELL = REPO_ROOT / "install.ps1"def _write_executable(path: Path, content: str) -> None:@@ -387,6 +388,35 @@ def test_install_script_continues_when_node_install_fails(tmp_path):assert "avibe-os 9.9.9" in version_result.stdout+def test_install_script_probes_the_same_libreoffice_path_as_memory(tmp_path):+ home_dir = tmp_path / "home"+ home_dir.mkdir()+ path_dir = tmp_path / "path-bin"+ path_dir.mkdir()+ uv_log = tmp_path / "uv-tool-bin-dir.txt"++ _write_fake_uv(path_dir / "uv", uv_log)++ env = os.environ.copy()+ env["HOME"] = str(home_dir)+ env["PATH"] = os.pathsep.join([str(path_dir), "/usr/bin", "/bin"])+ env["VIBE_INSTALL_SKIP_NODE"] = "1"++ _write_executable(path_dir / "soffice", "#!/usr/bin/env bash\nexit 0\n")+ result = _install(env, cwd=tmp_path)++ assert result.returncode == 0, result.stdout + result.stderr+ assert "LibreOffice is not available" in result.stdout+ assert "Memory will skip Word, Excel, PowerPoint" in result.stdout+ assert "LibreOffice is available for Memory Office attachment capture" not in result.stdout+ assert 'PATH="/usr/bin:/bin" command -v soffice' in INSTALL_SCRIPT.read_text()+ powershell = INSTALL_POWERSHELL.read_text()+ assert 'Test-Command "soffice"' not in powershell+ assert '@("/usr/bin/soffice", "/bin/soffice")' not in powershell+ assert "Memory Office attachment capture is unavailable on native Windows" in powershell+ assert "Install LibreOffice from https://www.libreoffice.org/" not in powershell++def test_install_script_continues_when_show_runtime_prepare_fails(tmp_path):home_dir = tmp_path / "home"home_dir.mkdir()diff --git a/tests/test_memory_admission.py b/tests/test_memory_admission.pyindex 64e722526..3d979b117 100644--- a/tests/test_memory_admission.py+++ b/tests/test_memory_admission.py@@ -3,7 +3,9 @@from __future__ import annotationsimport asyncio+import ioimport os+import zipfilefrom pathlib import Pathfrom types import SimpleNamespace@@ -508,6 +510,14 @@ def _upload(uploads: Path, filename: str, mimetype: str) -> SimpleNamespace:return SimpleNamespace(name=filename, mimetype=mimetype, local_path=str(path))+def _xlsx_bytes() -> bytes:+ payload = io.BytesIO()+ with zipfile.ZipFile(payload, "w") as archive:+ archive.writestr("[Content_Types].xml", b"content types")+ archive.writestr("xl/workbook.xml", b"workbook")+ return payload.getvalue()++def test_only_extensions_the_provider_can_parse_become_attachments(monkeypatch, tmp_path: Path) -> None:"""The runtime answers an unparseable extension with a permanent rejection.@@ -522,7 +532,8 @@ def test_only_extensions_the_provider_can_parse_become_attachments(monkeypatch,_upload(uploads, "notes.txt", "text/plain"),_upload(uploads, "export.json", "application/json"),_upload(uploads, "receipt.pdf", "application/pdf"),- # Needs LibreOffice, absent from the text-only runtime.+ # Office bytes that are not a convertible container stay out even when+ # LibreOffice is present, so a malformed xlsx cannot abort the batch._upload(uploads, "report.docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"),# In the runtime's IMAGE set, but needs the absent cairosvg support._upload(uploads, "logo.svg", "image/svg+xml"),@@ -535,6 +546,39 @@ def test_only_extensions_the_provider_can_parse_become_attachments(monkeypatch,assert [attachment.kind for attachment in converted] == ["doc", "pdf", "image"]+def test_workbench_office_uploads_require_soffice_and_convertible_bytes(+ monkeypatch, tmp_path: Path+) -> None:+ uploads = _uploads_dir(monkeypatch, tmp_path)+ monkeypatch.setattr(+ "core.memory.modality.office_conversion_available",+ lambda: True,+ )+ valid = uploads / "report.xlsx"+ valid.write_bytes(_xlsx_bytes())+ fake = _upload(+ uploads,+ "broken.docx",+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",+ )++ converted = workbench_capture_attachments(+ [+ SimpleNamespace(+ name="report.xlsx",+ mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",+ local_path=str(valid),+ ),+ fake,+ _upload(uploads, "logo.svg", "image/svg+xml"),+ ]+ )++ assert [attachment.name for attachment in converted] == ["report.xlsx"]+ assert [attachment.kind for attachment in converted] == ["doc"]+ assert [attachment.ext for attachment in converted] == ["xlsx"]++def test_workbench_turn_of_only_unparseable_uploads_is_not_captured(monkeypatch, tmp_path: Path) -> None:uploads = _uploads_dir(monkeypatch, tmp_path)ordinary = is_ordinary_workbench_text(diff --git a/tests/test_memory_attachments.py b/tests/test_memory_attachments.pyindex e253df9d6..5d6343783 100644--- a/tests/test_memory_attachments.py+++ b/tests/test_memory_attachments.py@@ -2,9 +2,11 @@ from __future__ import annotationsimport errnoimport hashlib+import ioimport osimport sqlite3import stat+import zipfilefrom dataclasses import fieldsfrom pathlib import Pathfrom types import SimpleNamespace@@ -57,6 +59,14 @@ def _attachment(path: Path, *, name: str | None = None) -> CaptureAttachment:)+def _xlsx_bytes() -> bytes:+ payload = io.BytesIO()+ with zipfile.ZipFile(payload, "w") as archive:+ archive.writestr("[Content_Types].xml", b"content types")+ archive.writestr("xl/workbook.xml", b"workbook")+ return payload.getvalue()++def _assert_pin_error(error: pytest.ExceptionInfo[AttachmentPinError], expected: str) -> None:assert error.value.error == expected@@ -157,6 +167,163 @@ def test_workbench_conversion_preserves_symlink_for_pin_rejection(attachment_roo_assert_pin_error(error, "memory_invalid_input")[email protected]("replacement", ["regular", "symlink"])+def test_pin_revalidates_workbench_office_copy_without_losing_siblings(+ attachment_roots,+ monkeypatch: pytest.MonkeyPatch,+ replacement: str,+) -> None:+ home, source_root = attachment_roots+ monkeypatch.setattr(+ "core.memory.modality.office_conversion_available",+ lambda: True,+ )+ office = _source_file(source_root, "report.xlsx", _xlsx_bytes())+ notes = _source_file(source_root, "notes.txt", b"keep this sibling")+ converted = workbench_capture_attachments(+ [+ SimpleNamespace(+ name="report.xlsx",+ mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",+ local_path=str(office),+ ),+ SimpleNamespace(+ name="notes.txt",+ mimetype="text/plain",+ local_path=str(notes),+ ),+ ]+ )+ assert [attachment.name for attachment in converted] == [+ "report.xlsx",+ "notes.txt",+ ]++ if replacement == "regular":+ office.write_bytes(b"not an Office container")+ else:+ office.unlink()+ office.symlink_to(notes)++ store = AttachmentPinStore()+ bundle = store.pin(converted)++ assert [attachment.name for attachment in bundle.attachments] == ["notes.txt"]+ assert bundle.attachments[0].storage_key.endswith("/00.txt")+ assert store.provider_attachments(bundle)[0].name == "notes.txt"+ staged = home / "memory" / "attachments" / "staging"+ assert list(staged.iterdir()) == []+ store.release(bundle.bundle_id)+++def test_workbench_long_office_display_name_keeps_suffix_through_pin(+ attachment_roots,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _home, source_root = attachment_roots+ monkeypatch.setattr(+ "core.memory.modality.office_conversion_available",+ lambda: True,+ )+ monkeypatch.setattr(+ "core.memory.modality.office_document_conversion_succeeds",+ lambda _path, **_kwargs: True,+ )+ office = _source_file(source_root, "upload.xlsx", _xlsx_bytes())+ long_name = f"{'report' * 100}.xlsx"++ converted = workbench_capture_attachments(+ [+ SimpleNamespace(+ name=long_name,+ mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",+ local_path=str(office),+ )+ ]+ )+ bundle = AttachmentPinStore().pin(converted)++ assert len(converted[0].name.encode("utf-8")) <= 512+ assert converted[0].name.endswith(".xlsx")+ assert bundle.attachments[0].name == converted[0].name+++def test_pin_requires_office_conversion_proof_without_losing_siblings(+ attachment_roots,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _home, source_root = attachment_roots+ monkeypatch.setattr(+ "core.memory.modality.office_conversion_available",+ lambda: True,+ )+ monkeypatch.setattr(+ "core.memory.modality.office_document_conversion_succeeds",+ lambda _path, **_kwargs: False,+ )+ office = _source_file(source_root, "report.xlsx", _xlsx_bytes())+ notes = _source_file(source_root, "notes.txt", b"keep this sibling")+ converted = workbench_capture_attachments(+ [+ SimpleNamespace(+ name="report.xlsx",+ mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",+ local_path=str(office),+ ),+ SimpleNamespace(+ name="notes.txt",+ mimetype="text/plain",+ local_path=str(notes),+ ),+ ]+ )++ bundle = AttachmentPinStore().pin(converted)++ assert [attachment.name for attachment in bundle.attachments] == ["notes.txt"]+ assert bundle.attachments[0].storage_key.endswith("/00.txt")+++def test_office_conversion_uses_one_bounded_budget_per_pin(+ attachment_roots,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _home, source_root = attachment_roots+ monkeypatch.setattr(+ "core.memory.modality.office_conversion_available",+ lambda: True,+ )+ observed_timeouts: list[float] = []++ def conversion_succeeds(_path: Path, *, timeout_seconds: float) -> bool:+ observed_timeouts.append(timeout_seconds)+ return True++ monkeypatch.setattr(+ "core.memory.modality.office_document_conversion_succeeds",+ conversion_succeeds,+ )+ clock = iter([100.0, 105.0, 131.0])+ monkeypatch.setattr(attachment_module.time, "monotonic", lambda: next(clock))+ first = _source_file(source_root, "first.xlsx", _xlsx_bytes())+ second = _source_file(source_root, "second.xlsx", _xlsx_bytes())+ converted = workbench_capture_attachments(+ [+ SimpleNamespace(+ name=path.name,+ mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",+ local_path=str(path),+ )+ for path in (first, second)+ ]+ )++ bundle = AttachmentPinStore().pin(converted)++ assert [attachment.name for attachment in bundle.attachments] == ["first.xlsx"]+ assert observed_timeouts == [25.0]++@pytest.mark.parametrize("uri_factory",[diff --git a/tests/test_memory_flush_coordinator.py b/tests/test_memory_flush_coordinator.pyindex 7cb57c2f0..164c60c2a 100644--- a/tests/test_memory_flush_coordinator.py+++ b/tests/test_memory_flush_coordinator.py@@ -3,8 +3,10 @@ from __future__ import annotationsimport asyncioimport errnoimport gc+import ioimport sqlite3import threading+import zipfilefrom collections import dequefrom datetime import UTC, datetime, timedeltafrom pathlib import Path@@ -149,6 +151,42 @@ def _pin_attachment_bundle() -> tuple[AttachmentPinStore, PinnedBundle, Path]:return attachment_store, bundle, pinned_path+def _xlsx_bytes() -> bytes:+ payload = io.BytesIO()+ with zipfile.ZipFile(payload, "w") as archive:+ archive.writestr("[Content_Types].xml", b"content types")+ archive.writestr("xl/workbook.xml", b"workbook")+ return payload.getvalue()+++def _pin_office_bundle(*, include_pdf: bool) -> tuple[AttachmentPinStore, PinnedBundle]:+ home = paths.get_vibe_remote_dir()+ source_root = home / "attachments" / "avibe"+ source_root.mkdir(parents=True, mode=0o700, exist_ok=True)+ source_root.chmod(0o700)+ specs = [("report.xlsx", "doc", _xlsx_bytes())]+ if include_pdf:+ specs.append(("evidence.pdf", "pdf", b"%PDF-1.7\npinned sibling"))+ attachments = []+ for name, kind, payload in specs:+ source = source_root / name+ source.write_bytes(payload)+ source.chmod(0o600)+ attachments.append(+ CaptureAttachment(+ kind=kind,+ name=name,+ uri=source.as_uri(),+ ext=source.suffix.lstrip("."),+ )+ )+ attachment_store = AttachmentPinStore(+ effective_home=home,+ source_root=source_root,+ )+ return attachment_store, attachment_store.pin(tuple(attachments))++def _enqueue_attachment_bundle(store: MemoryStore,bundle: PinnedBundle,@@ -3562,6 +3600,154 @@ async def test_attachment_preflight_failure_retries_caption_as_text_only(assert releases == [bundle.bundle_id]+async def test_delivery_rechecks_soffice_and_preserves_non_office_siblings(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ store = _store(tmp_path)+ monkeypatch.setattr(+ attachment_module.memory_modality,+ "office_conversion_available",+ lambda: True,+ )+ monkeypatch.setattr(+ attachment_module.memory_modality,+ "office_document_conversion_succeeds",+ lambda _path, **_kwargs: True,+ )+ attachment_store, bundle = _pin_office_bundle(include_pdf=True)+ original = _enqueue_attachment_bundle(+ store,+ bundle,+ source="soffice-removed-before-delivery",+ )+ monkeypatch.setattr(+ attachment_module.memory_modality,+ "office_conversion_available",+ lambda: False,+ )+ provider = FakeMemoryProvider()+ coordinator = SessionFlushCoordinator(+ store=store,+ provider=provider,+ enabled=lambda: True,+ attachment_store=attachment_store,+ )+ claimed = store.claim_due(+ lease_owner="worker",+ now="2026-01-01T00:00:00.000Z",+ )+ assert claimed is not None++ assert await coordinator.deliver(claimed, lease_owner="worker")++ settled = store.get_queue_row(original.source_message_digest)+ assert settled is not None+ assert settled.state == "delivered"+ assert [item.name for item in provider.captures[0].attachments] == ["evidence.pdf"]+ assert store.attachment_bundle_sets() == (frozenset(), frozenset())+++async def test_delivery_reproves_office_conversion_with_a_resolvable_binary(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ store = _store(tmp_path)+ monkeypatch.setattr(+ attachment_module.memory_modality,+ "office_conversion_available",+ lambda: True,+ )+ monkeypatch.setattr(+ attachment_module.memory_modality,+ "office_document_conversion_succeeds",+ lambda _path, **_kwargs: True,+ )+ attachment_store, bundle = _pin_office_bundle(include_pdf=True)+ original = _enqueue_attachment_bundle(+ store,+ bundle,+ source="soffice-broken-before-delivery",+ )+ monkeypatch.setattr(+ attachment_module.memory_modality,+ "office_document_conversion_succeeds",+ lambda _path, **_kwargs: False,+ )+ provider = FakeMemoryProvider()+ coordinator = SessionFlushCoordinator(+ store=store,+ provider=provider,+ enabled=lambda: True,+ attachment_store=attachment_store,+ )+ claimed = store.claim_due(+ lease_owner="worker",+ now="2026-01-01T00:00:00.000Z",+ )+ assert claimed is not None++ assert await coordinator.deliver(claimed, lease_owner="worker")++ settled = store.get_queue_row(original.source_message_digest)+ assert settled is not None+ assert settled.state == "delivered"+ assert [item.name for item in provider.captures[0].attachments] == ["evidence.pdf"]+++async def test_delivery_settles_captionless_office_when_soffice_disappears(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ store = _store(tmp_path)+ monkeypatch.setattr(+ attachment_module.memory_modality,+ "office_conversion_available",+ lambda: True,+ )+ monkeypatch.setattr(+ attachment_module.memory_modality,+ "office_document_conversion_succeeds",+ lambda _path, **_kwargs: True,+ )+ attachment_store, bundle = _pin_office_bundle(include_pdf=False)+ original = _enqueue_attachment_bundle(+ store,+ bundle,+ source="captionless-soffice-removed-before-delivery",+ payload_text="",+ )+ monkeypatch.setattr(+ attachment_module.memory_modality,+ "office_conversion_available",+ lambda: False,+ )+ provider = FakeMemoryProvider()+ coordinator = SessionFlushCoordinator(+ store=store,+ provider=provider,+ enabled=lambda: True,+ attachment_store=attachment_store,+ )+ claimed = store.claim_due(+ lease_owner="worker",+ now="2026-01-01T00:00:00.000Z",+ )+ assert claimed is not None++ assert not await coordinator.deliver(claimed, lease_owner="worker")++ settled = store.get_queue_row(original.source_message_digest)+ assert settled is not None+ assert (settled.state, settled.attempts, settled.last_error) == (+ "dead",+ 1,+ "memory_invalid_input",+ )+ assert provider.captures == []+ assert store.attachment_bundle_sets() == (frozenset(), frozenset())++@pytest.mark.parametrize("error_code",["UNSUPPORTED_FORMAT", "CAPABILITY_UNAVAILABLE"],diff --git a/tests/test_memory_im_attachments.py b/tests/test_memory_im_attachments.pyindex 58032775e..37bbd7edf 100644--- a/tests/test_memory_im_attachments.py+++ b/tests/test_memory_im_attachments.py@@ -1,6 +1,8 @@from __future__ import annotations+import ioimport os+import zipfilefrom pathlib import Pathimport pytest@@ -42,6 +44,14 @@ async def _materialize()+def _xlsx_bytes() -> bytes:+ payload = io.BytesIO()+ with zipfile.ZipFile(payload, "w") as archive:+ archive.writestr("[Content_Types].xml", b"content types")+ archive.writestr("xl/workbook.xml", b"workbook")+ return payload.getvalue()++@pytest.mark.asyncioasync def test_memory_selection_normalizes_missing_mime_without_losing_siblings(tmp_path: Path,@@ -149,6 +159,59 @@ async def test_memory_selection_counts_only_supported_survivors(tmp_path: Path)batch.lease.release()+async def test_memory_selection_skips_office_without_soffice(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr("core.memory.modality.office_conversion_available", lambda: False)+ batch = await _materialize(+ tmp_path / "avibe-home",+ [+ ("valid.pdf", "application/pdf", b"%PDF-1.7\n", 9),+ (+ "report.xlsx",+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",+ _xlsx_bytes(),+ None,+ ),+ ],+ )++ selected = select_memory_attachments(batch.lease)++ assert [item.name for item in selected.attachments] == ["valid.pdf"]+ assert selected.skipped == ("unsupported_type",)+ batch.lease.release()+++async def test_memory_selection_admits_office_when_soffice_is_present(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr("core.memory.modality.office_conversion_available", lambda: True)+ batch = await _materialize(+ tmp_path / "avibe-home",+ [+ (+ "report.xlsx",+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",+ _xlsx_bytes(),+ None,+ ),+ ("valid.pdf", "application/pdf", b"%PDF-1.7\n", 9),+ ],+ )++ selected = select_memory_attachments(batch.lease)++ assert [item.name for item in selected.attachments] == ["report.xlsx", "valid.pdf"]+ assert [item.kind for item in selected.attachments] == ["doc", "pdf"]+ assert selected.skipped == ()+ batch.lease.release()++@pytest.mark.asyncioasync def test_long_materialized_filename_preserves_supported_extension(tmp_path: Path,diff --git a/tests/test_memory_modality.py b/tests/test_memory_modality.pyindex 129fe796e..1e43e32b7 100644--- a/tests/test_memory_modality.py+++ b/tests/test_memory_modality.py@@ -1,13 +1,20 @@+import io+import struct+import subprocessimport sys+import zipfilefrom pathlib import Pathfrom types import ModuleTypeimport pytest+import core.memory.modality as modality_modulefrom core.memory.modality import (+ OFFICE_ATTACHMENT_EXTENSIONS,PINNED_UPSTREAM_EXCLUDED_EXTENSIONS,SUPPORTED_ATTACHMENT_EXTENSIONS,classify_pinned_attachment,+ office_conversion_available,pinned_modality_contract_matches,pinned_modality_contract_script,)@@ -112,3 +119,465 @@ def test_pinned_modality_admission_script_accepts_supported_upstream_containers(monkeypatch.setitem(sys.modules, "everalgo.types.modality", modality)exec(pinned_modality_contract_script(), {})+++_OLE_MAGIC = b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1"+_RTF_MAGIC = b"{\\rtf office"+_FREE_SECTOR = 0xFFFFFFFF+_END_OF_CHAIN = 0xFFFFFFFE+_FAT_SECTOR = 0xFFFFFFFD+++def _ole_document(*stream_names: str) -> bytes:+ def directory_entry(+ name: str,+ object_type: int,+ *,+ start_sector: int = _END_OF_CHAIN,+ size: int = 0,+ child: int = _FREE_SECTOR,+ right: int = _FREE_SECTOR,+ ) -> bytes:+ entry = bytearray(128)+ encoded_name = (name + "\0").encode("utf-16le")+ entry[: len(encoded_name)] = encoded_name+ struct.pack_into(+ "<HBBIII",+ entry,+ 64,+ len(encoded_name),+ object_type,+ 1,+ _FREE_SECTOR,+ right,+ child,+ )+ struct.pack_into("<I", entry, 116, start_sector)+ struct.pack_into("<Q", entry, 120, size)+ return bytes(entry)++ header = bytearray(512)+ header[:8] = _OLE_MAGIC+ struct.pack_into("<HHHHH", header, 24, 0x3E, 3, 0xFFFE, 9, 6)+ struct.pack_into(+ "<IIIIIIIII",+ header,+ 40,+ 0,+ 1,+ 0,+ 0,+ 4096,+ _END_OF_CHAIN,+ 0,+ _END_OF_CHAIN,+ 0,+ )+ struct.pack_into(+ "<109I",+ header,+ 76,+ 1,+ *([_FREE_SECTOR] * 108),+ )++ entries = [directory_entry("Root Entry", 5, child=1)]+ streams: list[bytes] = []+ fat = [_FREE_SECTOR] * 128+ fat[0] = _END_OF_CHAIN+ fat[1] = _FAT_SECTOR+ for index, stream_name in enumerate(stream_names):+ start_sector = 2 + (8 * index)+ right = index + 2 if index + 1 < len(stream_names) else _FREE_SECTOR+ entries.append(+ directory_entry(+ stream_name,+ 2,+ start_sector=start_sector,+ size=4096,+ right=right,+ )+ )+ for sector in range(start_sector, start_sector + 7):+ fat[sector] = sector + 1+ fat[start_sector + 7] = _END_OF_CHAIN+ streams.append(stream_name.encode("ascii").ljust(4096, b"\0"))++ directory = b"".join(entries).ljust(512, b"\0")+ return bytes(+ header+ + directory+ + struct.pack("<128I", *fat)+ + b"".join(streams)+ )+++def _office_zip(*entries: str, mimetype: str | None = None) -> bytes:+ payload = io.BytesIO()+ with zipfile.ZipFile(payload, "w") as archive:+ for entry in entries:+ archive.writestr(entry, mimetype if entry == "mimetype" else b"content")+ return payload.getvalue()+++def test_classifier_keeps_svg_out_of_the_live_allowlist(tmp_path: Path) -> None:+ path = _write_private(+ tmp_path / "logo.svg",+ b'<svg xmlns="http://www.w3.org/2000/svg"></svg>',+ )++ assert "svg" in PINNED_UPSTREAM_EXCLUDED_EXTENSIONS+ assert classify_pinned_attachment("logo.svg", "image/svg+xml", path) is None+++def test_office_probe_uses_sidecar_path_and_macos_fallback(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ seen: dict[str, object] = {}++ def fake_which(name: str, path: str | None = None) -> str | None:+ seen["name"] = name+ seen["path"] = path+ return None++ monkeypatch.setattr("core.memory.modality.shutil.which", fake_which)+ monkeypatch.setattr(+ "core.memory.modality._MACOS_SOFFICE",+ tmp_path / "missing-soffice",+ )+ assert office_conversion_available() is False+ assert seen == {"name": "soffice", "path": "/usr/bin:/bin"}++ fallback = _write_private(tmp_path / "soffice", b"")+ monkeypatch.setattr("core.memory.modality._MACOS_SOFFICE", fallback)+ assert office_conversion_available() is False++ fallback.chmod(0o700)+ assert office_conversion_available() is True+++def test_office_conversion_preflight_uses_isolated_bounded_soffice(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ source = _write_private(tmp_path / "report.xlsx", b"office")+ converter = tmp_path / "soffice"+ seen: dict[str, object] = {}++ def fake_run(command, **kwargs):+ seen["command"] = command+ seen["kwargs"] = kwargs+ output_dir = Path(command[command.index("--outdir") + 1])+ (output_dir / "report.pdf").write_bytes(b"%PDF-1.7\nconverted")+ return subprocess.CompletedProcess(command, 0)++ monkeypatch.setattr(modality_module, "_office_converter_path", lambda: converter)+ monkeypatch.setattr(modality_module.subprocess, "run", fake_run)++ assert modality_module.office_document_conversion_succeeds(source) is True+ command = seen["command"]+ kwargs = seen["kwargs"]+ assert "--headless" in command+ assert "--convert-to" in command+ assert any(str(value).startswith("-env:UserInstallation=file:") for value in command)+ assert kwargs["env"]["PATH"] == "/usr/bin:/bin"+ assert kwargs["timeout"] == 30+ assert kwargs["check"] is False+++def test_classifier_skips_office_without_soffice(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr("core.memory.modality.office_conversion_available", lambda: False)+ path = _write_private(+ tmp_path / "report.docx",+ _office_zip("[Content_Types].xml", "word/document.xml"),+ )++ assert classify_pinned_attachment(+ "report.docx",+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",+ path,+ ) is None+++def test_classifier_accepts_office_when_soffice_is_present(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr("core.memory.modality.office_conversion_available", lambda: True)+ path = _write_private(+ tmp_path / "report.xlsx",+ _office_zip("[Content_Types].xml", "xl/workbook.xml"),+ )++ assert classify_pinned_attachment(+ "report.xlsx",+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",+ path,+ ) == ("doc", "xlsx")+++def test_classifier_rejects_office_bytes_that_are_not_convertible(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr("core.memory.modality.office_conversion_available", lambda: True)+ path = _write_private(tmp_path / "report.docx", b"not an office container")++ assert classify_pinned_attachment(+ "report.docx",+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",+ path,+ ) is None+++def test_classifier_rejects_an_ordinary_zip_renamed_as_office(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr("core.memory.modality.office_conversion_available", lambda: True)+ path = _write_private(tmp_path / "report.docx", _office_zip("notes.txt"))++ assert classify_pinned_attachment(+ "report.docx",+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",+ path,+ ) is None+++def test_classifier_rejects_office_zip_entry_amplification_before_opening(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ entries = ["[Content_Types].xml", "word/document.xml"]+ entries.extend(+ f"padding/{index}"+ for index in range(modality_module._MAX_OFFICE_ZIP_ENTRIES - 1)+ )+ payload = bytearray(_office_zip(*entries))+ eocd_offset = payload.rfind(modality_module._ZIP_EOCD_SIGNATURE)+ assert eocd_offset >= 0+ struct.pack_into("<HH", payload, eocd_offset + 8, 1, 1)+ path = _write_private(tmp_path / "report.docx", bytes(payload))+ monkeypatch.setattr("core.memory.modality.office_conversion_available", lambda: True)++ def refuse_zipfile(*_args, **_kwargs):+ raise AssertionError("entry-count rejection must precede ZipFile construction")++ monkeypatch.setattr(modality_module.zipfile, "ZipFile", refuse_zipfile)++ assert classify_pinned_attachment(+ "report.docx",+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",+ path,+ ) is None++[email protected]("budget", ["member", "aggregate"])+def test_classifier_rejects_office_zip_uncompressed_size_amplification(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ budget: str,+) -> None:+ entries = ["[Content_Types].xml", "word/document.xml"]+ if budget == "aggregate":+ entries.extend(f"padding/{index}" for index in range(4))+ payload = bytearray(_office_zip(*entries))+ central_offsets: list[int] = []+ search_offset = 0+ while True:+ central_offset = payload.find(+ modality_module._ZIP_CENTRAL_DIRECTORY_SIGNATURE,+ search_offset,+ )+ if central_offset < 0:+ break+ central_offsets.append(central_offset)+ search_offset = central_offset + 4+ assert len(central_offsets) == len(entries)++ if budget == "member":+ sizes = [modality_module._MAX_OFFICE_ZIP_MEMBER_BYTES + 1]+ else:+ aggregate_member_size = (+ modality_module._MAX_OFFICE_ZIP_TOTAL_UNCOMPRESSED_BYTES // 4+ ) + 1+ assert aggregate_member_size < modality_module._MAX_OFFICE_ZIP_MEMBER_BYTES+ sizes = [1, 1, *([aggregate_member_size] * 4)]+ for central_offset, uncompressed_size in zip(central_offsets, sizes):+ struct.pack_into("<L", payload, central_offset + 24, uncompressed_size)++ path = _write_private(tmp_path / "report.docx", bytes(payload))+ monkeypatch.setattr("core.memory.modality.office_conversion_available", lambda: True)++ assert classify_pinned_attachment(+ "report.docx",+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",+ path,+ ) is None+++ ("filename", "mimetype"),+ [+ ("report.pages", "application/vnd.apple.pages"),+ ("slides.key", "application/vnd.apple.keynote"),+ ("budget.numbers", "application/vnd.apple.numbers"),+ ],+)+def test_classifier_accepts_registered_iwork_mime_types(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ filename: str,+ mimetype: str,+) -> None:+ monkeypatch.setattr("core.memory.modality.office_conversion_available", lambda: True)+ path = _write_private(tmp_path / filename, _office_zip("Index/Document.iwa"))++ assert classify_pinned_attachment(filename, mimetype, path) == (+ "doc",+ Path(filename).suffix.lstrip("."),+ )+++def test_classifier_requires_the_mime_for_the_same_office_extension(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr("core.memory.modality.office_conversion_available", lambda: True)+ path = _write_private(+ tmp_path / "report.docx",+ _office_zip("[Content_Types].xml", "word/document.xml"),+ )++ assert classify_pinned_attachment(+ "report.docx",+ "application/vnd.ms-excel",+ path,+ ) is None+++def test_classifier_requires_the_registered_odf_package_mimetype(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr("core.memory.modality.office_conversion_available", lambda: True)+ valid = _write_private(+ tmp_path / "notes.odt",+ _office_zip(+ "mimetype",+ "content.xml",+ mimetype="application/vnd.oasis.opendocument.text",+ ),+ )+ wrong = _write_private(+ tmp_path / "sheet.odt",+ _office_zip(+ "mimetype",+ "content.xml",+ mimetype="application/vnd.oasis.opendocument.spreadsheet",+ ),+ )++ assert classify_pinned_attachment(+ "notes.odt",+ "application/vnd.oasis.opendocument.text",+ valid,+ ) == ("doc", "odt")+ assert classify_pinned_attachment(+ "sheet.odt",+ "application/vnd.oasis.opendocument.text",+ wrong,+ ) is None+++ ("filename", "mimetype", "streams"),+ [+ (+ "legacy.doc",+ "application/msword",+ ("WordDocument", "1Table"),+ ),+ (+ "slides.ppt",+ "application/vnd.ms-powerpoint",+ ("PowerPoint Document",),+ ),+ (+ "budget.xls",+ "application/vnd.ms-excel",+ ("Workbook",),+ ),+ ],+)+def test_classifier_accepts_structurally_valid_legacy_office_documents(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ filename: str,+ mimetype: str,+ streams: tuple[str, ...],+) -> None:+ monkeypatch.setattr("core.memory.modality.office_conversion_available", lambda: True)+ path = _write_private(tmp_path / filename, _ole_document(*streams))++ assert classify_pinned_attachment(filename, mimetype, path) == (+ "doc",+ Path(filename).suffix.lstrip("."),+ )+++ ("filename", "mimetype", "payload"),+ [+ (+ "legacy.doc",+ "application/msword",+ _OLE_MAGIC + b"truncated",+ ),+ (+ "legacy.doc",+ "application/msword",+ _ole_document("Workbook"),+ ),+ (+ "slides.ppt",+ "application/vnd.ms-powerpoint",+ _ole_document("WordDocument", "1Table"),+ ),+ (+ "budget.xls",+ "application/vnd.ms-excel",+ _ole_document("PowerPoint Document"),+ ),+ ],+)+def test_classifier_rejects_invalid_or_wrong_application_ole_containers(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ filename: str,+ mimetype: str,+ payload: bytes,+) -> None:+ monkeypatch.setattr("core.memory.modality.office_conversion_available", lambda: True)+ path = _write_private(tmp_path / filename, payload)++ assert classify_pinned_attachment(filename, mimetype, path) is None+++def test_classifier_accepts_rtf_container(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr("core.memory.modality.office_conversion_available", lambda: True)+ path = _write_private(tmp_path / "notes.rtf", _RTF_MAGIC)++ assert classify_pinned_attachment(+ "notes.rtf",+ "application/rtf",+ path,+ ) == ("doc", "rtf")+ assert "rtf" in OFFICE_ATTACHMENT_EXTENSIONSdiff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 6599a74c8..f9658114e 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -4579,7 +4579,7 @@"dashscope": "DashScope"},"multimodalTitle": "IM attachment processing model (optional)",- "multimodalHelp": "When fully configured, eligible attachments from bound direct messages are sent to this OpenAI-compatible vision endpoint for Memory capture.",+ "multimodalHelp": "When fully configured, eligible attachments from bound direct messages are sent to this OpenAI-compatible vision endpoint for Memory capture. Office documents also require LibreOffice on this machine and are unavailable on native Windows. SVG and video stay excluded.","multimodalHelpLabel": "About IM attachment processing","multimodalClearLabel": "Disable IM attachment capture","baseUrl": "Base URL",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 1c386001f..49f8a0b24 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -4579,7 +4579,7 @@"dashscope": "DashScope"},"multimodalTitle": "IM 附件处理模型(可选)",- "multimodalHelp": "完整配置后,已绑定私聊中的合规附件会发送到这个兼容 OpenAI 格式的视觉模型端点,用于记忆捕获。",+ "multimodalHelp": "完整配置后,已绑定私聊中的合规附件会发送到这个兼容 OpenAI 格式的视觉模型端点,用于记忆捕获。Office 文档还需要本机已安装 LibreOffice,且原生 Windows 当前不可用。SVG 和视频仍不支持。","multimodalHelpLabel": "关于 IM 附件处理","multimodalClearLabel": "关闭 IM 附件捕获","baseUrl": "Base URL",diff --git a/uv.lock b/uv.lockindex b01e8665d..b2362c1d9 100644--- a/uv.lock+++ b/uv.lock@@ -312,6 +312,7 @@ dependencies = [{ name = "lark-oapi" },{ name = "markdown-it-py" },{ name = "markdown-to-mrkdwn" },+ { name = "olefile" },{ name = "packaging" },{ name = "prometheus-client" },{ name = "psutil" },@@ -353,6 +354,7 @@ requires-dist = [{ name = "lark-oapi", specifier = ">=1.4.0" },{ name = "markdown-it-py", specifier = ">=4.2.0" },{ name = "markdown-to-mrkdwn", specifier = ">=0.2.0" },+ { name = "olefile", specifier = ">=0.47" },{ name = "packaging", specifier = ">=23.0" },{ name = "prometheus-client", specifier = ">=0.20.0" },{ name = "psutil", specifier = ">=5.9.0" },@@ -1362,6 +1364,15 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/b7/da/7d22601b625e241d4f23ef1ebff8acfc60da633c9e7e7922e24d10f592b3/multidict-6.7.0-py3-none-any.whl", hash = "sha256:394fc5c42a333c9ffc3e421a4c85e08580d990e08b99f6bf35b4132114c5dcb3", size = 12317, upload-time = "2025-10-06T14:52:29.272Z" },]+[[package]]+name = "olefile"+version = "0.47"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/69/1b/077b508e3e500e1629d366249c3ccb32f95e50258b231705c09e3c7a4366/olefile-0.47.zip", hash = "sha256:599383381a0bf3dfbd932ca0ca6515acd174ed48870cbf7fee123d698c192c1c", size = 112240, upload-time = "2023-12-01T16:22:53.025Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/17/d3/b64c356a907242d719fc668b71befd73324e47ab46c8ebbbede252c154b2/olefile-0.47-py2.py3-none-any.whl", hash = "sha256:543c7da2a7adadf21214938bb79c83ea12b473a4b6ee4ad4bf854e7715e13d1f", size = 114565, upload-time = "2023-12-01T16:22:51.518Z" },+]+[[package]]name = "packaging"version = "26.2"