Skip to content

The agent that grows with you

16.1 KB
Raw Blame
"""Attachment staging: image sniffing, size caps, per-session attachment dirs, path resolution.

Bodies are rebound onto server.py's globals at install time (see
method_ctx.bind_module), so they reference server.py globals bare.
"""

from __future__ import annotations

import os
import re as _re

from .method_ctx import HandlerRegistry, bind_module

_registry = HandlerRegistry()


# Bytes sent inline in a data URL: the native Desktop reader's own attach cap (Electron reads at most
# 256 MiB), which also bounds the base64 text and its decoded copy held in memory. A host file named
# by path is copied in chunks and has no cap; a browser upload's copy has the tighter browser cap.
_ATTACHMENT_MAX_BYTES = 256 * 1024 * 1024
_ATTACH_BYTES_MAX_BYTES = 25 * 1024 * 1024
_PDF_ATTACH_MAX_BYTES = 50 * 1024 * 1024
_PDF_ATTACH_MAX_PAGES = 25

# Leading magic bytes -> file extension, for filename-less uploads.
_IMAGE_MAGIC: tuple[tuple[bytes, str], ...] = (
    (b"\x89PNG\r\n\x1a\n", ".png"), (b"\xff\xd8\xff", ".jpg"), (b"GIF87a", ".gif"),
    (b"GIF89a", ".gif"), (b"BM", ".bmp"))

# Context-ref values containing any of these must be quoted (desktop formatRefValue parity).
_ATTACHMENT_REF_NEEDS_QUOTING_RE = _re.compile(r"""[\s()\[\]{}<>"'`]""")
del _re  # bodies are rebound onto server globals: import inside functions only


def _too_large(label: str, size: int, max_bytes: int) -> str:
    """The refusal of a payload over its cap: ``image too large (31457280 bytes; cap is 25 MB)``."""
    return f"{label} too large ({size} bytes; cap is {max_bytes // (1024 * 1024)} MB)"


def _b64_payload(
    raw: str, data_url_re: str, flags: int, *, max_bytes: int, label: str = "attachment",
) -> bytes:
    """Strip an optional ``data:...;base64,`` wrapper and all whitespace, then strictly decode.
    Over *max_bytes* raises ``OverflowError`` with the refusal, before decoding when the base64
    text is already too long."""
    import base64 as _base64
    import re as _re
    cleaned = (raw or "").strip()
    if m := _re.match(data_url_re, cleaned, flags):
        cleaned = m.group(1)
    cleaned = _re.sub(r"\s+", "", cleaned)
    if len(cleaned) > 4 * ((max_bytes + 2) // 3):
        padding = len(cleaned) - len(cleaned.rstrip("="))
        raise OverflowError(_too_large(label, len(cleaned) * 3 // 4 - padding, max_bytes))
    payload = _base64.b64decode(cleaned, validate=True)
    if len(payload) > max_bytes:
        raise OverflowError(_too_large(label, len(payload), max_bytes))
    return payload


def _decode_attach_base64(
    raw: str, *, mime_prefix: str, max_bytes: int, label: str = "attachment",
) -> bytes | None:
    """Decode a (``data:<mime_prefix>...;base64,``-wrapped) payload; None when invalid."""
    import re as _re
    try:
        return _b64_payload(
            raw, rf"^data:{_re.escape(mime_prefix)}[a-zA-Z0-9.+-]*;base64,(.*)$", _re.DOTALL,
            max_bytes=max_bytes, label=label)
    except OverflowError:
        raise
    except Exception:
        return None


def _decode_attach_payload(
    rid, raw_b64: str, *, mime_prefix: str, max_bytes: int, label: str, empty_msg: str):
    """``(bytes, None)`` or ``(None, error)``: 4017 on bad/empty base64, 4018 over *max_bytes*."""
    try:
        data = _decode_attach_base64(
            raw_b64, mime_prefix=mime_prefix, max_bytes=max_bytes, label=label)
    except OverflowError as exc:
        return None, _err(rid, 4018, str(exc))
    if data is None:
        return None, _err(rid, 4017, "data is not valid base64")
    if not data:
        return None, _err(rid, 4017, empty_msg)
    return data, None


def _sniff_image_ext(img_bytes: bytes, filename: str = "") -> str:
    """Extension from the filename hint, else magic bytes (WebP: RIFF container), else ``.png``."""
    from pathlib import Path
    if filename and (suffix := Path(filename).suffix.lower()):
        return suffix
    head = img_bytes[:16]
    if head.startswith(b"RIFF") and head[8:12] == b"WEBP":
        return ".webp"
    return next((ext for sig, ext in _IMAGE_MAGIC if head.startswith(sig)), ".png")


def _allowed_image_extensions() -> frozenset[str]:
    try:
        from cli import _IMAGE_EXTENSIONS
        return frozenset(_IMAGE_EXTENSIONS)
    except Exception:
        return frozenset({".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp"})


def _session_home_dir(session: dict, name: str) -> Path:
    """``<session home>/<name>``, anchored on the session's stored ``profile_home``: attach
    RPCs run BEFORE ``prompt.submit`` installs the profile HERMES_HOME override, while
    the sandbox mounts and the vision host-read allowlist resolve the *session profile's*
    dirs at run time — writing anywhere else means the agent can never see the file.

    ``attachments`` instead follows the session workspace when the profile's config opts
    in via ``attachments.storage: workspace`` (#110662): staging then lands inside the
    allowed ref root, so the ``@file:`` ref stays workspace-relative."""
    profile_home = session.get("profile_home")
    if name == "attachments" and _profile_attachments_storage(profile_home) == "workspace":
        if workspace := _session_attachments_workspace(session):
            return workspace / ".hermes" / "attachments"
    return (Path(profile_home) if profile_home else _hermes_home) / name


def _profile_attachments_storage(profile_home) -> str:
    """The session profile's ``attachments.storage`` ("" unless it opts into "workspace").

    Read from THAT profile's config.yaml — ``file.attach`` runs before ``prompt.submit``
    installs the profile scope, so the process config still belongs to the launch profile
    (same reason as ``_profile_configured_cwd``).

    Best-effort, including when the config backend cannot serve the profile: ``""`` keeps the
    profile-home store, which the sandbox mounts and the vision allowlist always cover, so the
    attachment still reaches the agent (by an absolute instead of a workspace-relative ref)."""
    import contextlib as _contextlib
    from hermes_cli.config_backend import ConfigBackendUnavailable
    home = Path(profile_home) if profile_home else _hermes_home
    try:
        with _contextlib.suppress(Exception):
            from hermes_cli.config_backend import config_exists
            from hermes_cli.config_effective import load_user_config_effective
            cfg_path = home / "config.yaml"
            if config_exists(cfg_path):
                attachments_cfg = load_user_config_effective(cfg_path).get("attachments")
                if isinstance(attachments_cfg, dict):
                    return str(attachments_cfg.get("storage") or "").strip().lower()
    except ConfigBackendUnavailable as exc:
        logger.warning("attachments.storage for %s unavailable (%s); staging in the profile home", home, exc.code)
    return ""


def _session_attachments_workspace(session: dict) -> Path | None:
    """The session workspace when ``attachments.storage: workspace`` can actually write to it.

    Only a workspace on THIS host can hold gateway-staged files: an ssh-profile cwd lives
    on the remote execution host and a cwd that doesn't exist locally can't be vouched
    for, so both keep the bind-mounted ``<profile home>/attachments`` that container and
    remote backends receive (#76577)."""
    import contextlib as _contextlib
    if _cwd_is_remote(session.get("profile_home")):
        return None
    with _contextlib.suppress(Exception):
        workspace = Path(_session_cwd(session)).resolve()
        if workspace.is_dir():
            return workspace
    return None


def _session_images_dir(session: dict) -> Path:
    return _session_home_dir(session, "images")


def stage_image_bytes(directory, img_bytes: bytes, ext: str, *, prefix: str):
    """Private, collision-free staging shared by local and canonical byte uploads."""
    import os
    from pathlib import Path
    import tempfile
    directory = Path(directory)
    directory.mkdir(mode=0o700, parents=True, exist_ok=True)
    fd, name = tempfile.mkstemp(dir=directory, prefix=prefix + "_", suffix=ext)
    path = Path(name)
    try:
        with os.fdopen(fd, "wb") as output:
            output.write(img_bytes)
            output.flush()
            os.fsync(output.fileno())
    except BaseException:
        path.unlink(missing_ok=True)
        raise
    return path


def _queue_attached_image(session: dict, img_bytes: bytes, ext: str, *, prefix: str) -> Path:
    """Write image bytes into the session images dir and queue them for the next submit."""
    session["image_counter"] = session.get("image_counter", 0) + 1
    img_dir = _session_images_dir(session)
    try:
        # mkstemp allocation is atomic across sessions sharing the profile images dir (main #b4faf6587e9's
        # cross-session collision fix holds without the counter-named xb probe loop).
        img_path = stage_image_bytes(img_dir, img_bytes, ext, prefix=prefix)
    except Exception:
        session["image_counter"] = max(0, session["image_counter"] - 1)
        raise
    session.setdefault("attached_images", []).append(str(img_path))
    return img_path


def _format_ref_value(value: str) -> str:
    """Quote a value with whitespace/brackets/quotes so the ``@file:`` ref round-trips."""
    if not value or not _ATTACHMENT_REF_NEEDS_QUOTING_RE.search(value):
        return value
    for q in ("`", '"', "'"):
        if q not in value:
            return f"{q}{value}{q}"
    return value


def _attachment_ref_path(session: dict, target: Path) -> str:
    """Workspace-relative path for an attachment, or the absolute path if outside."""
    workspace = Path(_session_cwd(session)).resolve()
    try:
        return str(target.resolve().relative_to(workspace)).replace(os.sep, "/")
    except ValueError:
        return str(target.resolve())


def _sanitize_attachment_name(name: str) -> str:
    import re as _re
    candidate = _re.sub(r"[\x00-\x1f]+", "_", Path(str(name or "").strip()).name)
    return candidate.strip().strip(".") or "attachment"


def _read_attachment_bytes(path: Path, max_bytes: int) -> bytes:
    # Bound the actual read, not just stat(): the source can grow after inspection.
    with path.open("rb") as source:
        payload = source.read(max_bytes + 1)
        if len(payload) > max_bytes:
            raise ValueError(_too_large("attachment", os.fstat(source.fileno()).st_size, max_bytes))
    return payload


def _stage_browser_file_attachment(session: dict, staged_upload: object, name: str) -> tuple[Path, bool]:
    """Copy a browser upload (the Webapp upload route's ``staged_upload`` receipt) into this session.

    Source and destination may be different profiles on the same installation (an owner-routed
    tile can receive a foreground browser pick); the caller decides which source homes this
    connection may reach. The receipt is resolved back to exactly the staged layout under its
    source home, which must still be a live profile (``hermes_cli/staged_uploads.py``). From there
    the copy is the native Desktop's out-of-workspace file attach, capped at the browser limit.
    """
    from hermes_constants import WEBAPP_ATTACHMENT_MAX_BYTES
    from hermes_cli.staged_uploads import parse_staged_upload, resolve_staged_upload

    raw_home, raw_path = parse_staged_upload(staged_upload)
    source = resolve_staged_upload(Path(raw_home), raw_path)
    # Copied into attachments/ even inside the workspace: the upload route prunes its staging after
    # 7 days. attachments/ is also visible to container/SSH terminal backends through cache mounts.
    return _stage_session_file_attachment(
        session, raw_path=str(source), data_url="", name=name, max_bytes=WEBAPP_ATTACHMENT_MAX_BYTES,
        staged=True)


def _referenced_in_place(session: dict, path: Path, workspace: Path, *, staged: bool) -> bool:
    """Whether an attached host file is referenced where it is: inside the workspace, and not a
    browser upload staged in the profile's ``uploads/`` (pruned after 7 days, so always copied)."""
    if staged or not path.is_relative_to(workspace):
        return False
    try:
        from hermes_cli.staged_uploads import is_staged_upload
    except ImportError:
        # An install without the web stack (fastapi) has no upload route that could stage one.
        return True
    profile_home = session.get("profile_home")
    return not is_staged_upload(Path(profile_home) if profile_home else _hermes_home, path)


def _stage_session_file_attachment(
    session: dict, *, raw_path: str, data_url: str, name: str, max_bytes: int | None = None,
    staged: bool = False,
) -> tuple[Path, bool]:
    """Make a desktop file attachment available to the gateway agent: ``(stored_path, uploaded)``.
    Inside the workspace -> as-is; gateway-visible but outside -> copied into ``attachments/``
    (bind-mounted into container backends so ``@file:`` resolves in the sandbox); not on the
    gateway -> ``data_url`` bytes decoded into ``attachments/``. A browser upload (*staged*, or a
    path in the profile's ``uploads/``) is always copied. ``max_bytes`` caps the copy of a
    browser upload; a host file is copied whatever its size, inline bytes up to
    ``_ATTACHMENT_MAX_BYTES``."""
    workspace = Path(_session_cwd(session)).resolve()
    resolved = None
    if raw_path:
        try:
            from cli import _detect_file_drop, _resolve_attachment_path, _split_path_input
        except Exception:
            _detect_file_drop = None
        if _detect_file_drop is not None:
            dropped = _detect_file_drop(raw_path)
            if dropped:
                resolved = Path(dropped["path"]).resolve()
            else:
                path_token, _remainder = _split_path_input(raw_path)
                found = _resolve_attachment_path(path_token)
                resolved = Path(found).resolve() if found is not None else None
    if resolved is not None:
        if _referenced_in_place(session, resolved, workspace, staged=staged):
            return resolved, False
        # Without a cap the copy below streams the file, so its size never reaches memory.
        payload = None if max_bytes is None else _read_attachment_bytes(resolved, max_bytes)
        filename = resolved.name
    else:
        if not data_url:
            raise ValueError("file not found on gateway and no data_url provided")
        # Any media type (unlike the image-specific decoder); bare base64 also accepted.
        import binascii as _binascii
        import re as _re
        inline_max = _ATTACHMENT_MAX_BYTES if max_bytes is None else min(max_bytes, _ATTACHMENT_MAX_BYTES)
        try:
            payload = _b64_payload(
                data_url, r"^data:[^;,]*(?:;[^;,=]+=[^;,]+)*;base64,(.*)$", _re.DOTALL | _re.IGNORECASE,
                max_bytes=inline_max)
        except (ValueError, _binascii.Error) as exc:
            raise ValueError("invalid data_url payload") from exc
        filename = _sanitize_attachment_name(name or Path(str(raw_path or "")).name)
    root = _session_home_dir(session, "attachments")
    root.mkdir(parents=True, exist_ok=True)
    filename = _sanitize_attachment_name(filename)
    target = root / filename
    stem = Path(filename).stem or "attachment"
    suffix = Path(filename).suffix
    counter = 2
    # O_CREAT|O_EXCL: never follows a planted (dangling) symlink, never races a same-name upload.
    while True:
        try:
            # Windows CREATE_NEW follows a dangling symlink and creates its target outside root;
            # an existing link of any kind is an occupied name on every platform.
            if os.path.lexists(target):
                raise FileExistsError(target)
            upload = target.open("xb")
        except FileExistsError:
            target = root / f"{stem}-{counter}{suffix}"
            counter += 1
        else:
            break
    try:
        with upload:
            if payload is None:
                import shutil as _shutil
                with resolved.open("rb") as source:
                    _shutil.copyfileobj(source, upload, 1024 * 1024)
            else:
                upload.write(payload)
    except Exception:
        target.unlink(missing_ok=True)
        raise
    return target.resolve(), True


def register(server) -> None:
    """Publish this module's helpers + handlers onto ``server``, rebound to its globals."""
    bind_module(globals(), server, skip=("_",))