     1→import hashlib
     2→from datetime import datetime, timezone
     3→
     4→from mirage.backend.base import BaseBackend
     5→from mirage.backend.filetype import guess_type
     6→from mirage.types import FileStat, FileType
     7→
     8→
     9→class MemoryBackend(BaseBackend):
    10→    """
    11→    In-memory backend backed by a plain dict. No external dependencies.
    12→    Useful for tests, ephemeral scratch space, and as a cache target.
    13→
    14→    Internal layout:
    15→        _files: dict[str, bytes]  — path → content
    16→        _dirs:  set[str]          — explicit directory paths
    17→    """
    18→
    19→    def __init__(self) -> None:
    20→        self._files: dict[str, bytes] = {}
    21→        self._dirs: set[str] = {"/"}
    22→        self._modified: dict[str, str] = {}  # path → ISO timestamp
    23→
    24→    # ── helpers ─────────────────────────────────────────────────────────────
    25→
    26→    def _norm(self, path: str) -> str:
    27→        """Normalise to absolute path without trailing slash."""
    28→        p = "/" + path.strip("/")
    29→        return p
    30→
    31→    def _now(self) -> str:
    32→        return datetime.now(timezone.utc).isoformat()
    33→
    34→    def _parent(self, path: str) -> str:
    35→        parts = path.rsplit("/", 1)
    36→        return parts[0] or "/"
    37→
    38→    # ── ops ─────────────────────────────────────────────────────────────────
    39→
    40→    def read(self, path: str, offset: int, size: int) -> bytes:
    41→        p = self._norm(path)
    42→        if p not in self._files:
    43→            raise FileNotFoundError(p)
    44→        return self._files[p][offset:offset + size]
    45→
    46→    def readdir(self,
    47→                path: str,
    48→                cursor: str | None = None) -> tuple[list[str], str | None]:
    49→        p = self._norm(path)
    50→        if p not in self._dirs:
    51→            raise FileNotFoundError(p)
    52→        prefix = p.rstrip("/") + "/"
    53→        # direct children only
    54→        seen: set[str] = set()
    55→        for key in list(self._files) + list(self._dirs):
    56→            if key == p:
    57→                continue
    58→            if key.startswith(prefix):
    59→                remainder = key[len(prefix):]
    60→                child = remainder.split("/")[0]
    61→                if child:
    62→                    seen.add(prefix + child)
    63→        names = sorted(seen)
    64→        # simple offset-based pagination via cursor
    65→        start = int(cursor) if cursor else 0
    66→        page = names[start:]
    67→        return page, None  # no pagination needed for in-memory
    68→
    69→    def stat(self, path: str) -> FileStat:
    70→        p = self._norm(path)
    71→        if p in self._dirs:
    72→            return FileStat(name=p.rsplit("/", 1)[-1] or "/",
    73→                            size=None,
    74→                            modified=self._modified.get(p),
    75→                            type=FileType.DIRECTORY)
    76→        if p in self._files:
    77→            data = self._files[p]
    78→            return FileStat(
    79→                name=p.rsplit("/", 1)[-1],
    80→                size=len(data),
    81→                modified=self._modified.get(p),
    82→                type=guess_type(p),
    83→            )
    84→        raise FileNotFoundError(p)
    85→
    86→    def open(self, path: str, flags: int) -> int:
    87→        raise NotImplementedError("open/release are FUSE-only")
    88→
    89→    def release(self, fh: int) -> None:
    90→        raise NotImplementedError("open/release are FUSE-only")
    91→
    92→    def write(self, path: str, offset: int, data: bytes) -> int:
    93→        p = self._norm(path)
    94→        if p not in self._files:
    95→            raise FileNotFoundError(p)
    96→        existing = self._files[p]
    97→        # pad if offset beyond current size
    98→        if offset > len(existing):
    99→            existing = existing + b"\x00" * (offset - len(existing))
   100→        self._files[p] = existing[:offset] + data + existing[offset +
   101→                                                             len(data):]
   102→        self._modified[p] = self._now()
   103→        return len(data)
   104→
   105→    def create(self, path: str) -> None:
   106→        p = self._norm(path)
   107→        parent = self._parent(p)
   108→        if parent != "/" and parent not in self._dirs:
   109→            raise FileNotFoundError(
   110→                f"parent directory does not exist: {parent}")
   111→        self._files[p] = b""
   112→        self._modified[p] = self._now()
   113→
   114→    def unlink(self, path: str) -> None:
   115→        p = self._norm(path)
   116→        if p not in self._files:
   117→            raise FileNotFoundError(p)
   118→        del self._files[p]
   119→        self._modified.pop(p, None)
   120→
   121→    def rmdir(self, path: str) -> None:
   122→        p = self._norm(path)
   123→        if p not in self._dirs:
   124→            raise FileNotFoundError(p)
   125→        prefix = p.rstrip("/") + "/"
   126→        children = [
   127→            k for k in list(self._files) + list(self._dirs)
   128→            if k.startswith(prefix) and k != p
   129→        ]
   130→        if children:
   131→            raise OSError(f"directory not empty: {p}")
   132→        self._dirs.discard(p)
   133→
   134→    def mkdir(self, path: str) -> None:
   135→        p = self._norm(path)
   136→        parent = self._parent(p)
   137→        if parent != "/" and parent not in self._dirs:
   138→            raise FileNotFoundError(
   139→                f"parent directory does not exist: {parent}")
   140→        self._dirs.add(p)
   141→        self._modified[p] = self._now()
   142→
   143→    def rename(self, src: str, dst: str) -> None:
   144→        s, d = self._norm(src), self._norm(dst)
   145→        if s in self._files:
   146→            self._files[d] = self._files.pop(s)
   147→            self._modified[d] = self._modified.pop(s, self._now())
   148→        elif s in self._dirs:
   149→            self._dirs.discard(s)
   150→            self._dirs.add(d)
   151→            self._modified[d] = self._modified.pop(s, self._now())
   152→            # move all children
   153→            prefix = s.rstrip("/") + "/"
   154→            for key in list(self._files):
   155→                if key.startswith(prefix):
   156→                    new_key = d.rstrip("/") + "/" + key[len(prefix):]
   157→                    self._files[new_key] = self._files.pop(key)
   158→        else:
   159→            raise FileNotFoundError(s)
   160→
   161→    def truncate(self, path: str, size: int) -> None:
   162→        p = self._norm(path)
   163→        if p not in self._files:
   164→            raise FileNotFoundError(p)
   165→        data = self._files[p]
   166→        if size < len(data):
   167→            self._files[p] = data[:size]
   168→        else:
   169→            self._files[p] = data + b"\x00" * (size - len(data))
   170→        self._modified[p] = self._now()
   171→
   172→    # ── convenience ─────────────────────────────────────────────────────────
   173→
   174→    def checksum(self, path: str) -> str:
   175→        p = self._norm(path)
   176→        return hashlib.md5(self._files[p]).hexdigest()
   177→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


     1→from pydantic import BaseModel, ConfigDict, Field
     2→
     3→from mirage.backend.base import BaseBackend
     4→from mirage.backend.filetype import guess_type
     5→from mirage.types import FileStat
     6→
     7→
     8→class HTTPConfig(BaseModel):
     9→    model_config = ConfigDict(frozen=True, arbitrary_types_allowed=True)
    10→
    11→    base_url: str
    12→    headers: dict[str, str] = Field(default_factory=dict)
    13→    timeout: int = 30
    14→    readdir_fn: object = None
    15→
    16→
    17→class HTTPBackend(BaseBackend):
    18→    """
    19→    Read-only HTTP backend using httpx.
    20→
    21→    Maps virtual paths to URLs: base_url + path
    22→    e.g. base_url="https://data.example.com", path="/q1.json"
    23→         → GET https://data.example.com/q1.json
    24→
    25→    Requires: pip install mirage[http]
    26→
    27→    Write ops (write, create, unlink, etc.) raise NotImplementedError —
    28→    HTTP is read-only by design. Override to support writable HTTP APIs.
    29→
    30→    readdir() requires a user-supplied `readdir_fn` since HTTP has no
    31→    standard directory listing protocol.
    32→    """
    33→
    34→    def __init__(self, config: HTTPConfig) -> None:
    35→        self.config = config
    36→        self._client = self._make_client()
    37→
    38→    def _make_client(self):
    39→        try:
    40→            import httpx
    41→        except ImportError:
    42→            raise ImportError(
    43→                "httpx is required for HTTPBackend: pip install 'mirage[http]'"
    44→            )
    45→        return httpx.Client(
    46→            base_url=self.config.base_url,
    47→            headers=self.config.headers,
    48→            timeout=self.config.timeout,
    49→            follow_redirects=True,
    50→        )
    51→
    52→    def _url(self, path: str) -> str:
    53→        return self.config.base_url.rstrip("/") + "/" + path.lstrip("/")
    54→
    55→    # ── ops ─────────────────────────────────────────────────────────────────
    56→
    57→    def read(self, path: str, offset: int, size: int) -> bytes:
    58→        headers = {"Range": f"bytes={offset}-{offset + size - 1}"}
    59→        resp = self._client.get(self._url(path), headers=headers)
    60→        if resp.status_code == 416:
    61→            return b""
    62→        resp.raise_for_status()
    63→        return resp.content
    64→
    65→    def readdir(self,
    66→                path: str,
    67→                cursor: str | None = None) -> tuple[list[str], str | None]:
    68→        if self.config.readdir_fn is None:
    69→            raise NotImplementedError(
    70→                "HTTPBackend.readdir() requires a readdir_fn in HTTPConfig. "
    71→                "Provide a callable(path) -> list[str] for your API.")
    72→        names = self.config.readdir_fn(path)
    73→        return names, None
    74→
    75→    def stat(self, path: str) -> FileStat:
    76→        resp = self._client.head(self._url(path))
    77→        if resp.status_code == 404:
    78→            raise FileNotFoundError(path)
    79→        resp.raise_for_status()
    80→        size = int(resp.headers.get("content-length", 0)) or None
    81→        modified = resp.headers.get("last-modified")
    82→        etag = resp.headers.get("etag", "").strip('"') or None
    83→        extra = {"etag": etag} if etag else {}
    84→        return FileStat(
    85→            name=path.rstrip("/").rsplit("/", 1)[-1],
    86→            size=size,
    87→            modified=modified,
    88→            type=guess_type(path),
    89→            extra=extra,
    90→        )
    91→
    92→    def open(self, path: str, flags: int) -> int:
    93→        raise NotImplementedError("open/release are FUSE-only")
    94→
    95→    def release(self, fh: int) -> None:
    96→        raise NotImplementedError("open/release are FUSE-only")
    97→
    98→    # ── write ops — not supported ────────────────────────────────────────────
    99→
   100→    def write(self, path: str, offset: int, data: bytes) -> int:
   101→        raise NotImplementedError("HTTPBackend is read-only")
   102→
   103→    def create(self, path: str) -> None:
   104→        raise NotImplementedError("HTTPBackend is read-only")
   105→
   106→    def unlink(self, path: str) -> None:
   107→        raise NotImplementedError("HTTPBackend is read-only")
   108→
   109→    def rmdir(self, path: str) -> None:
   110→        raise NotImplementedError("HTTPBackend is read-only")
   111→
   112→    def mkdir(self, path: str) -> None:
   113→        raise NotImplementedError("HTTPBackend is read-only")
   114→
   115→    def rename(self, src: str, dst: str) -> None:
   116→        raise NotImplementedError("HTTPBackend is read-only")
   117→
   118→    def truncate(self, path: str, size: int) -> None:
   119→        raise NotImplementedError("HTTPBackend is read-only")
   120→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


     1→import base64
     2→
     3→import httpx
     4→
     5→from mirage.backend.base import BaseBackend
     6→from mirage.types import FileStat
     7→
     8→
     9→class ProxyBackend(BaseBackend):
    10→
    11→    def __init__(self,
    12→                 base_url: str,
    13→                 ws_id: str,
    14→                 timeout: int = 30,
    15→                 http_client: httpx.Client | None = None) -> None:
    16→        self._base_url = base_url.rstrip("/")
    17→        self._ws_id = ws_id
    18→        self._http = http_client or httpx.Client(timeout=timeout)
    19→
    20→    def _post(self, op: str, payload: dict) -> dict:
    21→        url = f"{self._base_url}/workspaces/{self._ws_id}/io/{op}"
    22→        resp = self._http.post(url, json=payload)
    23→        if resp.status_code == 404:
    24→            detail = resp.json().get("detail", "")
    25→            if "workspace" in detail:
    26→                raise KeyError(detail)
    27→            raise FileNotFoundError(payload.get("path", ""))
    28→        resp.raise_for_status()
    29→        return resp.json()
    30→
    31→    def read(self, path: str, offset: int, size: int) -> bytes:
    32→        r = self._post("read", {"path": path, "offset": offset, "size": size})
    33→        return base64.b64decode(r["data"])
    34→
    35→    def readdir(self,
    36→                path: str,
    37→                cursor: str | None = None) -> tuple[list[str], str | None]:
    38→        r = self._post("readdir", {"path": path, "cursor": cursor})
    39→        return r["entries"], r.get("cursor")
    40→
    41→    def stat(self, path: str) -> FileStat:
    42→        r = self._post("stat", {"path": path})
    43→        return FileStat(**r)
    44→
    45→    def open(self, path: str, flags: int) -> int:
    46→        raise NotImplementedError("open not supported on ProxyBackend")
    47→
    48→    def release(self, fh: int) -> None:
    49→        raise NotImplementedError("release not supported on ProxyBackend")
    50→
    51→    def write(self, path: str, offset: int, data: bytes) -> int:
    52→        encoded = base64.b64encode(data).decode()
    53→        r = self._post("write", {
    54→            "path": path,
    55→            "offset": offset,
    56→            "data": encoded
    57→        })
    58→        return r["written"]
    59→
    60→    def create(self, path: str) -> None:
    61→        self._post("create", {"path": path})
    62→
    63→    def unlink(self, path: str) -> None:
    64→        self._post("unlink", {"path": path})
    65→
    66→    def rmdir(self, path: str) -> None:
    67→        self._post("rmdir", {"path": path})
    68→
    69→    def mkdir(self, path: str) -> None:
    70→        self._post("mkdir", {"path": path})
    71→
    72→    def rename(self, src: str, dst: str) -> None:
    73→        self._post("rename", {"src": src, "dst": dst})
    74→
    75→    def truncate(self, path: str, size: int) -> None:
    76→        self._post("truncate", {"path": path, "size": size})
    77→
    78→    def fuse_cat(self, path: str) -> bytes:
    79→        r = self._post("fuse_cat", {"path": path})
    80→        return base64.b64decode(r["data"])
    81→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


     1→import re
     2→from datetime import timezone
     3→
     4→from pydantic import BaseModel, ConfigDict
     5→
     6→from mirage.backend.base import BaseBackend
     7→from mirage.backend.filetype import guess_type
     8→from mirage.types import FileStat, FileType
     9→
    10→
    11→class S3Config(BaseModel):
    12→    model_config = ConfigDict(frozen=True)
    13→
    14→    bucket: str
    15→    region: str | None = None
    16→    endpoint_url: str | None = None
    17→    aws_access_key_id: str | None = None
    18→    aws_secret_access_key: str | None = None
    19→    aws_profile: str | None = None
    20→    timeout: int = 30
    21→    proxy: str | None = None
    22→    select_threshold_bytes: int | None = 1 * 1024 * 1024  # 1 MB
    23→
    24→
    25→class S3Backend(BaseBackend):
    26→    """
    27→    S3-compatible backend using boto3.
    28→
    29→    Requires: pip install mirage[s3]
    30→
    31→    Key design decisions:
    32→    - read()  → GetObject with Range header (partial reads)
    33→    - readdir() → list_objects_v2 with paginator (handles >1000 keys)
    34→    - write()  → full PutObject (S3 has no partial write)
    35→    - grep()   → S3 Select for large files, full fetch for small files
    36→    - ls_l()   → list_objects_v2 already returns size+mtime, skip per-file stat
    37→    """
    38→
    39→    def __init__(self, config: S3Config) -> None:
    40→        self.config = config
    41→        self._client = self._make_client()
    42→
    43→    def _make_client(self):
    44→        try:
    45→            import boto3
    46→            from botocore.config import Config
    47→        except ImportError:
    48→            raise ImportError(
    49→                "boto3 is required for S3Backend: pip install 'mirage[s3]'")
    50→
    51→        kwargs: dict = {"service_name": "s3"}
    52→        c = self.config
    53→        if c.region:
    54→            kwargs["region_name"] = c.region
    55→        if c.endpoint_url:
    56→            kwargs["endpoint_url"] = c.endpoint_url
    57→        if c.aws_access_key_id and c.aws_secret_access_key:
    58→            kwargs["aws_access_key_id"] = c.aws_access_key_id
    59→            kwargs["aws_secret_access_key"] = c.aws_secret_access_key
    60→
    61→        cfg_kwargs: dict = {
    62→            "connect_timeout": c.timeout,
    63→            "read_timeout": c.timeout
    64→        }
    65→        if c.proxy:
    66→            cfg_kwargs["proxies"] = {"https": c.proxy, "http": c.proxy}
    67→
    68→        kwargs["config"] = Config(**cfg_kwargs)
    69→
    70→        if c.aws_profile:
    71→            session = boto3.Session(profile_name=c.aws_profile)
    72→            return session.client(**kwargs)
    73→        return boto3.client(**kwargs)
    74→
    75→    # ── key helpers ─────────────────────────────────────────────────────────
    76→
    77→    def _key(self, path: str) -> str:
    78→        """Convert virtual path to S3 key (strip leading slash)."""
    79→        return path.lstrip("/")
    80→
    81→    def _prefix(self, path: str) -> str:
    82→        """Directory prefix — always ends with '/' unless root."""
    83→        key = self._key(path)
    84→        if key and not key.endswith("/"):
    85→            key += "/"
    86→        return key
    87→
    88→    # ── ops ─────────────────────────────────────────────────────────────────
    89→
    90→    def read(self, path: str, offset: int, size: int) -> bytes:
    91→        end = offset + size - 1
    92→        resp = self._client.get_object(
    93→            Bucket=self.config.bucket,
    94→            Key=self._key(path),
    95→            Range=f"bytes={offset}-{end}",
    96→        )
    97→        return resp["Body"].read()
    98→
    99→    def readdir(self,
   100→                path: str,
   101→                cursor: str | None = None) -> tuple[list[str], str | None]:
   102→        prefix = self._prefix(path)
   103→        kwargs: dict = {
   104→            "Bucket": self.config.bucket,
   105→            "Prefix": prefix,
   106→            "Delimiter": "/",
   107→        }
   108→        if cursor:
   109→            kwargs["ContinuationToken"] = cursor
   110→
   111→        resp = self._client.list_objects_v2(**kwargs)
   112→
   113→        names: list[str] = []
   114→        # common prefixes = subdirectories
   115→        for cp in resp.get("CommonPrefixes") or []:
   116→            p = cp["Prefix"]
   117→            child = p.rstrip("/")
   118→            if child:
   119→                names.append(child)
   120→        # object keys = files
   121→        for obj in resp.get("Contents") or []:
   122→            key = obj["Key"]
   123→            relative = key[len(prefix):]
   124→            if relative and "/" not in relative:  # direct children only
   125→                names.append(key)
   126→
   127→        next_cursor = resp.get("NextContinuationToken")
   128→        return sorted(names), next_cursor
   129→
   130→    def stat(self, path: str) -> FileStat:
   131→        try:
   132→            resp = self._client.head_object(Bucket=self.config.bucket,
   133→                                            Key=self._key(path))
   134→            modified = resp["LastModified"].astimezone(
   135→                timezone.utc).isoformat()
   136→            return FileStat(
   137→                name=path.rstrip("/").rsplit("/", 1)[-1],
   138→                size=resp["ContentLength"],
   139→                modified=modified,
   140→                type=guess_type(path),
   141→                extra={"etag": resp.get("ETag", "").strip('"')},
   142→            )
   143→        except self._client.exceptions.NoSuchKey:
   144→            pass
   145→        except Exception as exc:
   146→            if not (hasattr(exc, "response")
   147→                    and exc.response.get("Error", {}).get("Code") == "404"):
   148→                raise
   149→        # key not found — check if it's a directory prefix
   150→        prefix = self._prefix(path)
   151→        resp = self._client.list_objects_v2(Bucket=self.config.bucket,
   152→                                            Prefix=prefix,
   153→                                            MaxKeys=1)
   154→        if resp.get("Contents") or resp.get("CommonPrefixes"):
   155→            return FileStat(
   156→                name=path.rstrip("/").rsplit("/", 1)[-1] or "/",
   157→                size=None,
   158→                type=FileType.DIRECTORY,
   159→            )
   160→        raise FileNotFoundError(path)
   161→
   162→    def open(self, path: str, flags: int) -> int:
   163→        raise NotImplementedError("open/release are FUSE-only")
   164→
   165→    def release(self, fh: int) -> None:
   166→        raise NotImplementedError("open/release are FUSE-only")
   167→
   168→    def write(self, path: str, offset: int, data: bytes) -> int:
   169→        # S3 has no partial write — we must do full replace
   170→        if offset != 0:
   171→            # fetch existing, splice, re-upload
   172→            existing = self.cat(path)
   173→            data = existing[:offset] + data + existing[offset + len(data):]
   174→        self._client.put_object(Bucket=self.config.bucket,
   175→                                Key=self._key(path),
   176→                                Body=data)
   177→        return len(data)
   178→
   179→    def create(self, path: str) -> None:
   180→        self._client.put_object(Bucket=self.config.bucket,
   181→                                Key=self._key(path),
   182→                                Body=b"")
   183→
   184→    def unlink(self, path: str) -> None:
   185→        self._client.delete_object(Bucket=self.config.bucket,
   186→                                   Key=self._key(path))
   187→
   188→    def rmdir(self, path: str) -> None:
   189→        prefix = self._prefix(path)
   190→        paginator = self._client.get_paginator("list_objects_v2")
   191→        for page in paginator.paginate(Bucket=self.config.bucket,
   192→                                       Prefix=prefix):
   193→            keys = [{"Key": obj["Key"]} for obj in page.get("Contents") or []]
   194→            if keys:
   195→                self._client.delete_objects(Bucket=self.config.bucket,
   196→                                            Delete={"Objects": keys})
   197→
   198→    def mkdir(self, path: str) -> None:
   199→        # S3 has no real directories — key prefix convention
   200→        prefix = self._prefix(path)
   201→        if prefix:
   202→            self._client.put_object(Bucket=self.config.bucket,
   203→                                    Key=prefix,
   204→                                    Body=b"")
   205→
   206→    def rename(self, src: str, dst: str) -> None:
   207→        self._client.copy_object(
   208→            Bucket=self.config.bucket,
   209→            CopySource={
   210→                "Bucket": self.config.bucket,
   211→                "Key": self._key(src)
   212→            },
   213→            Key=self._key(dst),
   214→        )
   215→        self._client.delete_object(Bucket=self.config.bucket,
   216→                                   Key=self._key(src))
   217→
   218→    def truncate(self, path: str, size: int) -> None:
   219→        data = self.cat(path)
   220→        if size < len(data):
   221→            data = data[:size]
   222→        else:
   223→            data = data + b"\x00" * (size - len(data))
   224→        self._client.put_object(Bucket=self.config.bucket,
   225→                                Key=self._key(path),
   226→                                Body=data)
   227→
   228→    # ── native overrides ────────────────────────────────────────────────────
   229→
   230→    def ls_l(self, path: str) -> list[FileStat]:
   231→        """list_objects_v2 returns size+mtime — skip per-file stat."""
   232→        prefix = self._prefix(path)
   233→        stats: list[FileStat] = []
   234→        paginator = self._client.get_paginator("list_objects_v2")
   235→        for page in paginator.paginate(Bucket=self.config.bucket,
   236→                                       Prefix=prefix,
   237→                                       Delimiter="/"):
   238→            for cp in page.get("CommonPrefixes") or []:
   239→                name = cp["Prefix"][len(prefix):].rstrip("/")
   240→                stats.append(
   241→                    FileStat(name=name, size=None, type=FileType.DIRECTORY))
   242→            for obj in page.get("Contents") or []:
   243→                key = obj["Key"]
   244→                name = key[len(prefix):]
   245→                if name and "/" not in name:
   246→                    modified = obj["LastModified"].astimezone(
   247→                        timezone.utc).isoformat()
   248→                    stats.append(
   249→                        FileStat(name=name,
   250→                                 size=obj["Size"],
   251→                                 modified=modified,
   252→                                 type=guess_type(name)))
   253→        return stats
   254→
   255→    def head(self, path: str, lines: int = 10) -> bytes:
   256→        threshold = self.config.select_threshold_bytes
   257→        if threshold is not None:
   258→            try:
   259→                s = self.stat(path)
   260→                if s.size and s.size > threshold:
   261→                    return self._head_select(path, lines)
   262→            except FileNotFoundError:
   263→                pass
   264→        return super().head(path, lines)
   265→
   266→    def _head_select(self, path: str, lines: int) -> bytes:
   267→        sql = f"SELECT * FROM S3Object LIMIT {int(lines)}"
   268→        try:
   269→            resp = self._client.select_object_content(
   270→                Bucket=self.config.bucket,
   271→                Key=self._key(path),
   272→                ExpressionType="SQL",
   273→                Expression=sql,
   274→                InputSerialization={
   275→                    "CSV": {
   276→                        "FileHeaderInfo": "NONE"
   277→                    },
   278→                    "CompressionType": "NONE"
   279→                },
   280→                OutputSerialization={"CSV": {}},
   281→            )
   282→            parts: list[str] = []
   283→            for event in resp["Payload"]:
   284→                if "Records" in event:
   285→                    parts.extend(
   286→                        event["Records"]["Payload"].decode().splitlines())
   287→            return "\n".join(parts[:lines]).encode()
   288→        except Exception:
   289→            return super().head(path, lines)
   290→
   291→    def presign(self, path: str, expires: int = 3600) -> str:
   292→        return self._client.generate_presigned_url(
   293→            "get_object",
   294→            Params={
   295→                "Bucket": self.config.bucket,
   296→                "Key": self._key(path)
   297→            },
   298→            ExpiresIn=expires,
   299→        )
   300→
   301→    def grep(self, pattern: str, path: str, flags: int = 0) -> list[str]:
   302→        """S3 Select for large files; full fetch for small files."""
   303→        threshold = self.config.select_threshold_bytes
   304→        if threshold is not None:
   305→            try:
   306→                s = self.stat(path)
   307→                if s.size and s.size > threshold:
   308→                    return self._grep_select(pattern, path)
   309→            except FileNotFoundError:
   310→                pass
   311→        return super().grep(pattern, path, flags)
   312→
   313→    def _grep_select(self, pattern: str, path: str) -> list[str]:
   314→        """S3 Select LIKE filter — regex unsupported, re-filtered in Python."""
   315→        escaped = (pattern.replace("'",
   316→                                   "''").replace("%",
   317→                                                 "\\%").replace("_", "\\_"))
   318→        sql = f"SELECT * FROM S3Object WHERE _1 LIKE '%{escaped}%'"
   319→        try:
   320→            resp = self._client.select_object_content(
   321→                Bucket=self.config.bucket,
   322→                Key=self._key(path),
   323→                ExpressionType="SQL",
   324→                Expression=sql,
   325→                InputSerialization={
   326→                    "CSV": {
   327→                        "FileHeaderInfo": "NONE"
   328→                    },
   329→                    "CompressionType": "NONE"
   330→                },
   331→                OutputSerialization={"CSV": {}},
   332→            )
   333→            lines: list[str] = []
   334→            for event in resp["Payload"]:
   335→                if "Records" in event:
   336→                    lines.extend(
   337→                        event["Records"]["Payload"].decode().splitlines())
   338→            compiled = re.compile(pattern)
   339→            return [line for line in lines if compiled.search(line)]
   340→        except Exception:
   341→            return super().grep(pattern, path)
   342→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


     1→from __future__ import annotations
     2→
     3→import time
     4→
     5→from mirage.backend.base import BaseBackend
     6→from mirage.backend.filetype import guess_type
     7→from mirage.types import (FileStat, Inode, MountMode, SyncPolicy, SyncResult,
     8→                          TransferStats)
     9→from mirage.workspace.cache import LRUCache
    10→from mirage.workspace.consistency import ConsistencyPolicy, is_fresh
    11→from mirage.workspace.mount import MountRegistry
    12→from mirage.workspace.sync import DirtyTracker
    13→
    14→
    15→class _PathLock:
    16→
    17→    def __init__(self, ws: Workspace, paths: list[str]) -> None:
    18→        self._ws = ws
    19→        self._paths = paths
    20→
    21→    def __enter__(self) -> _PathLock:
    22→        return self
    23→
    24→    def __exit__(self, *_: object) -> None:
    25→        self._ws.unlock_paths(self._paths)
    26→
    27→
    28→class Workspace:
    29→    """
    30→    Unified virtual filesystem over heterogeneous backends.
    31→
    32→    Mounts backends at virtual path prefixes and provides a command-level API
    33→    (cat, ls, write, cp, mv, rm, ...) with transparent caching
    34→    and write staging.
    35→
    36→    Example::
    37→
    38→        ws = Workspace(
    39→            {"/data/": S3Backend(S3Config(bucket="my-bucket")),
    40→             "/tmp/":  MemoryBackend()},
    41→            cache_limit="256MB",
    42→            sync_policy=SyncPolicy.STAGED,
    43→        )
    44→        content = ws.cat("/data/reports/q1.json")
    45→        ws.write("/tmp/summary.txt", b"hello")
    46→        ws.sync()
    47→    """
    48→
    49→    def __init__(
    50→        self,
    51→        backends: dict[str, BaseBackend | tuple],
    52→        cache_limit: str | int = "512MB",
    53→        sync_policy: SyncPolicy = SyncPolicy.STAGED,
    54→        mode: MountMode = MountMode.READ,
    55→        consistency: ConsistencyPolicy = ConsistencyPolicy.CACHED,
    56→        ttl_seconds: int = 300,
    57→    ) -> None:
    58→        self._registry = MountRegistry()
    59→        self._cache = LRUCache(cache_limit)
    60→        self._tracker = DirtyTracker()
    61→        self._sync_policy = sync_policy
    62→        self._ttl_seconds = ttl_seconds
    63→        self._locked_paths: set[str] = set()
    64→        self._transfer_stats: dict[str, TransferStats] = {}
    65→        self._created_at: float = time.monotonic()
    66→
    67→        for prefix, value in backends.items():
    68→            if isinstance(value, tuple) and len(value) == 3:
    69→                backend, mount_mode, mount_consistency = value
    70→            elif isinstance(value, tuple):
    71→                backend, mount_mode = value
    72→                mount_consistency = consistency
    73→            else:
    74→                backend = value
    75→                mount_mode = mode
    76→                mount_consistency = consistency
    77→            self._registry.mount(prefix, backend, mount_mode,
    78→                                 mount_consistency)
    79→
    80→    # ── mount management ────────────────────────────────────────────────────
    81→
    82→    def mount(
    83→            self,
    84→            prefix: str,
    85→            backend: BaseBackend,
    86→            mode: MountMode = MountMode.READ,
    87→            consistency: ConsistencyPolicy = ConsistencyPolicy.CACHED) -> None:
    88→        self._registry.mount(prefix, backend, mode, consistency)
    89→
    90→    def backend(self, path: str) -> BaseBackend:
    91→        backend, _, _ = self._registry.resolve(path)
    92→        return backend
    93→
    94→    # ── read ops ────────────────────────────────────────────────────────────
    95→
    96→    def cat(self, path: str) -> bytes:
    97→        inode = self._tracker.get(path)
    98→        if inode and inode.dirty:
    99→            entry = self._cache.get(path)
   100→            if entry is not None:

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


     1→from mirage.workspace.workspace import Workspace
     2→
     3→__all__ = ["Workspace"]
     4→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


     1→from mirage.backend.base import BaseBackend
     2→from mirage.types import MountMode
     3→from mirage.workspace.consistency import ConsistencyPolicy
     4→
     5→
     6→class Mount:
     7→
     8→    def __init__(
     9→            self,
    10→            prefix: str,
    11→            backend: BaseBackend,
    12→            mode: MountMode = MountMode.READ,
    13→            consistency: ConsistencyPolicy = ConsistencyPolicy.CACHED) -> None:
    14→        stripped = prefix.strip("/")
    15→        self.prefix = "/" + stripped + "/" if stripped else "/"
    16→        self.backend = backend
    17→        self.mode = mode
    18→        self.consistency = consistency
    19→
    20→
    21→class MountRegistry:
    22→    """
    23→    Longest-prefix-match router.
    24→
    25→    Given a virtual path like "/s3-prod/data/file.json", resolves to the
    26→    backend mounted at "/s3-prod/" and returns the stripped path
    27→    "/data/file.json".
    28→    """
    29→
    30→    def __init__(self) -> None:
    31→        self._mounts: list[Mount] = []
    32→
    33→    def mount(
    34→            self,
    35→            prefix: str,
    36→            backend: BaseBackend,
    37→            mode: MountMode = MountMode.READ,
    38→            consistency: ConsistencyPolicy = ConsistencyPolicy.CACHED) -> None:
    39→        m = Mount(prefix, backend, mode, consistency)
    40→        for existing in self._mounts:
    41→            if existing.prefix == m.prefix:
    42→                raise ValueError(f"duplicate mount prefix: {m.prefix!r}")
    43→        self._mounts.append(m)
    44→        self._mounts.sort(key=lambda x: len(x.prefix), reverse=True)
    45→
    46→    def resolve(self, path: str) -> tuple[BaseBackend, str, MountMode]:
    47→        """
    48→        Returns (backend, backend_path, mode).
    49→
    50→        backend_path has the mount prefix stripped.
    51→        Raises ValueError if no mount matches.
    52→        """
    53→        norm = "/" + path.strip("/")
    54→        # ensure trailing slash when checking prefix match for directories
    55→        for m in self._mounts:
    56→            if norm == m.prefix.rstrip("/") or norm.startswith(m.prefix):
    57→                backend_path = "/" + norm[len(m.prefix):]
    58→                return m.backend, backend_path, m.mode
    59→        raise ValueError(f"no mount matches path: {path!r}")
    60→
    61→    def mount_for(self, path: str) -> Mount:
    62→        norm = "/" + path.strip("/")
    63→        for m in self._mounts:
    64→            if norm == m.prefix.rstrip("/") or norm.startswith(m.prefix):
    65→                return m
    66→        raise ValueError(f"no mount matches path: {path!r}")
    67→
    68→    def mounts(self) -> list[Mount]:
    69→        return list(self._mounts)
    70→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


     1→import hashlib
     2→import time
     3→
     4→from mirage.backend.base import BaseBackend
     5→from mirage.types import Inode, SyncResult
     6→
     7→
     8→class DirtyTracker:
     9→    """
    10→    Tracks which virtual paths have local changes that haven't been synced
    11→    to their backing backend.
    12→
    13→    Lifecycle:
    14→        on_read()  — record baseline remote checksum (not dirty)
    15→        on_write() — update local checksum, mark dirty=True
    16→        on_sync()  — upload to backend, clear dirty flag
    17→    """
    18→
    19→    def __init__(self) -> None:
    20→        self._inodes: dict[str, Inode] = {}
    21→
    22→    # ── event hooks ─────────────────────────────────────────────────────────
    23→
    24→    def on_read(self, path: str, data: bytes, mount: str) -> None:
    25→        checksum = _md5(data)
    26→        if path in self._inodes:
    27→            inode = self._inodes[path]
    28→            inode.remote_checksum = checksum
    29→            inode.checksum = checksum
    30→            inode.size = len(data)
    31→            inode.dirty = False
    32→        else:
    33→            self._inodes[path] = Inode(
    34→                virtual_path=path,
    35→                backend_mount=mount,
    36→                checksum=checksum,
    37→                size=len(data),
    38→                remote_checksum=checksum,
    39→                dirty=False,
    40→            )
    41→
    42→    def on_write(self, path: str, data: bytes, mount: str) -> None:
    43→        checksum = _md5(data)
    44→        if path in self._inodes:
    45→            inode = self._inodes[path]
    46→            inode.checksum = checksum
    47→            inode.size = len(data)
    48→            inode.dirty = True
    49→        else:
    50→            self._inodes[path] = Inode(
    51→                virtual_path=path,
    52→                backend_mount=mount,
    53→                checksum=checksum,
    54→                size=len(data),
    55→                remote_checksum=None,
    56→                dirty=True,
    57→            )
    58→
    59→    def on_delete(self, path: str) -> None:
    60→        if path in self._inodes:
    61→            self._inodes[path].dirty = True
    62→            self._inodes[path].checksum = None
    63→            self._inodes[path].size = None
    64→
    65→    def on_sync(self, virtual_path: str, backend_path: str, data: bytes | None,
    66→                backend: BaseBackend) -> SyncResult:
    67→        """
    68→        Upload `data` to backend at `backend_path`. Pass None for deletions.
    69→        `virtual_path` tracks the inode; `backend_path` goes to the backend.
    70→        Returns a SyncResult describing the outcome.
    71→        """
    72→        inode = self._inodes.get(virtual_path)
    73→        op = "delete" if data is None else ("create" if (
    74→            inode and inode.remote_checksum is None) else "modify")
    75→        t0 = time.monotonic()
    76→        try:
    77→            if data is None:
    78→                backend.unlink(backend_path)
    79→            else:
    80→                backend.put(backend_path, data)

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


     1→import time
     2→from enum import Enum
     3→
     4→from mirage.backend.base import BaseBackend
     5→from mirage.types import FileStat
     6→from mirage.workspace.cache.entry import CacheEntry
     7→
     8→
     9→class ConsistencyPolicy(str, Enum):
    10→    CACHED = "cached"
    11→    LAZY = "lazy"
    12→    TTL = "ttl"
    13→    ALWAYS = "always"
    14→
    15→
    16→def is_fresh(
    17→    entry: CacheEntry,
    18→    consistency: ConsistencyPolicy,
    19→    ttl_seconds: int,
    20→    backend: BaseBackend,
    21→    backend_path: str,
    22→) -> tuple[bool, FileStat | None]:
    23→    if consistency == ConsistencyPolicy.CACHED:
    24→        return True, None
    25→    if consistency == ConsistencyPolicy.ALWAYS:
    26→        return False, None
    27→    if consistency == ConsistencyPolicy.TTL:
    28→        if (time.monotonic() - entry.cached_at) < ttl_seconds:
    29→            return True, None
    30→    try:
    31→        remote = backend.stat(backend_path)
    32→    except FileNotFoundError:
    33→        return False, None
    34→    return metadata_matches(entry, remote), remote
    35→
    36→
    37→def metadata_matches(entry: CacheEntry, remote: FileStat) -> bool:
    38→    remote_etag = remote.extra.get("etag")
    39→    if entry.etag and remote_etag:
    40→        return entry.etag == remote_etag
    41→    if entry.modified and remote.modified:
    42→        return entry.modified == remote.modified
    43→    if entry.size is not None and remote.size is not None:
    44→        return entry.size == remote.size
    45→    return False
    46→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


     1→from mirage.workspace.cache.entry import CacheEntry
     2→from mirage.workspace.cache.store import LRUCache
     3→
     4→__all__ = ["CacheEntry", "LRUCache"]
     5→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


     1→from __future__ import annotations
     2→
     3→from typing import TYPE_CHECKING
     4→
     5→if TYPE_CHECKING:
     6→    from mirage.workspace import Workspace
     7→
     8→_EAGER_THRESHOLD = 1 * 1024 * 1024  # 1MB
     9→
    10→
    11→class FuseOp:
    12→
    13→    name: str = "base"
    14→
    15→    def on_open(self, ws: Workspace, path: str, size: int) -> dict:
    16→        return {"eager": size < _EAGER_THRESHOLD}
    17→
    18→    def read(self, ws: Workspace, path: str, offset: int, size: int,
    19→             ctx: dict) -> bytes:
    20→        if ctx.get("eager"):
    21→            if "data" not in ctx:
    22→                ctx["data"] = ws.cat(path)
    23→            return ctx["data"][offset:offset + size]
    24→        return ws.read(path, offset, size)
    25→
    26→    def write(self, ws: Workspace, path: str, offset: int, data: bytes,
    27→              ctx: dict) -> int:
    28→        buf = ctx.setdefault("write_buf", [])
    29→        buf.append((offset, data))
    30→        return len(data)
    31→
    32→    def on_flush(self, ws: Workspace, path: str, ctx: dict) -> None:
    33→        buf = ctx.get("write_buf")
    34→        if not buf:
    35→            return
    36→        existing = b""
    37→        try:
    38→            existing = ws.cat(path)
    39→        except FileNotFoundError:
    40→            pass
    41→        merged = bytearray(existing)
    42→        for off, chunk in buf:
    43→            end = off + len(chunk)
    44→            if end > len(merged):
    45→                merged.extend(b"\0" * (end - len(merged)))
    46→            merged[off:off + len(chunk)] = chunk
    47→        ws.write(path, bytes(merged))
    48→        ctx["write_buf"] = []
    49→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


     1→import errno
     2→import os
     3→import stat
     4→import time
     5→import uuid
     6→
     7→import mfusepy as fuse
     8→
     9→from mirage.fuse.base import FuseOp
    10→from mirage.fuse.ops_log import OpsLog
    11→from mirage.fuse.registry import FuseOpRegistry
    12→from mirage.workspace import Workspace
    13→
    14→_ENV_AGENT_ID = "MIRAGE_AGENT_ID"
    15→_MIRAGE_DIR = "/.mirage"
    16→_MIRAGE_WHOAMI = "/.mirage/whoami"
    17→
    18→
    19→class MirageFS(fuse.Operations):
    20→
    21→    use_ns = True
    22→
    23→    def __init__(self,
    24→                 ws: Workspace,
    25→                 agent_id: str | None = None,
    26→                 fuse_registry: FuseOpRegistry | None = None) -> None:
    27→        self.ws = ws
    28→        self.agent_id = (agent_id or os.environ.get(_ENV_AGENT_ID)
    29→                         or f"agent-{uuid.uuid4().hex[:8]}")
    30→        self._now = time.time_ns()
    31→        self._prefixes = [m.prefix for m in ws._registry._mounts]
    32→        self._ops_log = OpsLog()
    33→        self._fuse_registry = fuse_registry or FuseOpRegistry()
    34→        self._handles: dict[int, dict] = {}
    35→        self._handle_ops: dict[int, FuseOp] = {}
    36→        self._next_fh = 1
    37→
    38→    def _whoami_content(self) -> bytes:
    39→        mounts = [m.prefix for m in self.ws._registry._mounts]
    40→        lines = [
    41→            f"agent: {self.agent_id}",
    42→            "cwd: /",
    43→            f"mounts: {', '.join(mounts)}",
    44→        ]
    45→        return ("\n".join(lines) + "\n").encode()
    46→
    47→    def _dir_stat(self) -> dict:
    48→        return {
    49→            "st_mode": stat.S_IFDIR | 0o755,
    50→            "st_nlink": 2,
    51→            "st_uid": os.getuid(),
    52→            "st_gid": os.getgid(),
    53→            "st_size": 0,
    54→            "st_atime": self._now,
    55→            "st_mtime": self._now,
    56→            "st_ctime": self._now,
    57→        }
    58→
    59→    def _file_stat(self, size: int) -> dict:
    60→        return {
    61→            "st_mode": stat.S_IFREG | 0o644,
    62→            "st_nlink": 1,
    63→            "st_uid": os.getuid(),
    64→            "st_gid": os.getgid(),
    65→            "st_size": size,
    66→            "st_atime": self._now,
    67→            "st_mtime": self._now,
    68→            "st_ctime": self._now,
    69→        }
    70→
    71→    def _is_virtual_dir(self, path: str) -> bool:
    72→        normalized = path.rstrip("/") + "/"
    73→        for p in self._prefixes:
    74→            if p.startswith(normalized) or p.rstrip("/") == path.rstrip("/"):
    75→                return True
    76→        return False
    77→
    78→    def _virtual_children(self, path: str) -> list[str]:
    79→        normalized = path.rstrip("/") + "/" if path != "/" else "/"
    80→        children = set()

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


     1→import importlib
     2→import importlib.util
     3→from typing import Any
     4→
     5→from mirage.fuse import FUSE_OPS
     6→from mirage.fuse.registry import FuseOpRegistry
     7→
     8→
     9→def load_fuse_op_class(spec: str) -> type[Any]:
    10→    if ":" not in spec:
    11→        raise ValueError(
    12→            f"invalid fuse op spec {spec!r}, expected 'source:ClassName'")
    13→
    14→    source, class_name = spec.rsplit(":", 1)
    15→
    16→    if "/" in source or source.endswith(".py"):
    17→        module_spec = importlib.util.spec_from_file_location(
    18→            "_mirage_user_fuse_op", source)
    19→        if module_spec is None or module_spec.loader is None:
    20→            raise ValueError(f"cannot load script {source!r}")
    21→        module = importlib.util.module_from_spec(module_spec)
    22→        try:
    23→            module_spec.loader.exec_module(module)
    24→        except FileNotFoundError:
    25→            raise ValueError(f"cannot load script {source!r}")
    26→    else:
    27→        module = importlib.import_module(source)
    28→
    29→    if not hasattr(module, class_name):
    30→        raise ValueError(f"{class_name!r} not found in {source!r}")
    31→
    32→    return getattr(module, class_name)
    33→
    34→
    35→def build_registry_from_config(fuse_ops: dict) -> FuseOpRegistry:
    36→    registry = FuseOpRegistry()
    37→    for pattern, value in fuse_ops.items():
    38→        if isinstance(value, str):
    39→            if value in FUSE_OPS:
    40→                registry.register(pattern, FUSE_OPS[value])
    41→            else:
    42→                cls = load_fuse_op_class(value)
    43→                registry.register(pattern, cls())
    44→        elif isinstance(value, dict):
    45→            handler = value.get("handler", "")
    46→            if handler in FUSE_OPS:
    47→                registry.register(pattern, FUSE_OPS[handler])
    48→            else:
    49→                cls = load_fuse_op_class(handler)
    50→                args = value.get("args", {})
    51→                registry.register(pattern, cls(**args))
    52→    return registry
    53→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


     1→import subprocess
     2→import sys
     3→import threading
     4→import time
     5→
     6→import mfusepy as fuse
     7→
     8→from mirage.fuse.fs import MirageFS
     9→from mirage.workspace import Workspace
    10→
    11→
    12→def _run_fuse(fs: MirageFS, mountpoint: str, foreground: bool) -> None:
    13→    fuse.FUSE(fs, mountpoint, nothreads=True, foreground=foreground)
    14→
    15→
    16→def mount_background(ws: Workspace,
    17→                     mountpoint: str,
    18→                     agent_id: str | None = None) -> threading.Thread:
    19→    fs = MirageFS(ws, agent_id=agent_id)
    20→    t = threading.Thread(target=_run_fuse,
    21→                         args=(fs, mountpoint, True),
    22→                         daemon=True)
    23→    t.start()
    24→    time.sleep(0.3)
    25→    return t
    26→
    27→
    28→def mount(ws: Workspace | None = None,
    29→          mountpoint: str = "",
    30→          foreground: bool = True,
    31→          agent_id: str | None = None,
    32→          fs: MirageFS | None = None) -> None:
    33→    if fs is None:
    34→        fs = MirageFS(ws, agent_id=agent_id)
    35→    t = threading.Thread(
    36→        target=_run_fuse,
    37→        args=(fs, mountpoint, foreground),
    38→        daemon=True,
    39→    )
    40→    t.start()
    41→    try:
    42→        while t.is_alive():
    43→            t.join(timeout=0.5)
    44→    except KeyboardInterrupt:
    45→        print("\nUnmounting...", flush=True)
    46→        if sys.platform == "darwin":
    47→            subprocess.run(
    48→                ["diskutil", "unmount", "force", mountpoint],
    49→                capture_output=True,
    50→            )

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


     1→from mirage.fuse.backend.default import DefaultFuseOp
     2→from mirage.fuse.backend.local.local import LocalFuseOp
     3→from mirage.fuse.backend.local.memory import MemoryFuseOp
     4→from mirage.fuse.backend.object_storage.s3 import S3FuseOp
     5→from mirage.fuse.base import FuseOp
     6→from mirage.fuse.filetype.csv import CsvFuseOp
     7→from mirage.fuse.filetype.parquet import ParquetFuseOp
     8→
     9→FUSE_OPS: dict[str, FuseOp] = {
    10→    "default": DefaultFuseOp(),
    11→    "s3": S3FuseOp(),
    12→    "memory": MemoryFuseOp(),
    13→    "local": LocalFuseOp(),
    14→    "parquet": ParquetFuseOp(),
    15→    "csv": CsvFuseOp(),
    16→}
    17→
    18→__all__ = [
    19→    "FuseOp",
    20→    "CsvFuseOp",
    21→    "DefaultFuseOp",
    22→    "LocalFuseOp",
    23→    "MemoryFuseOp",
    24→    "ParquetFuseOp",
    25→    "S3FuseOp",
    26→    "FUSE_OPS",
    27→]
    28→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


     1→from __future__ import annotations
     2→
     3→import fnmatch
     4→from typing import TYPE_CHECKING
     5→
     6→from mirage.fuse import FUSE_OPS, FuseOp
     7→
     8→if TYPE_CHECKING:
     9→    from mirage.workspace import Workspace
    10→
    11→_BACKEND_OP_MAP: dict[str, str] = {
    12→    "S3Backend": "s3",
    13→    "R2Backend": "s3",
    14→    "MemoryBackend": "memory",
    15→    "LocalBackend": "local",
    16→}
    17→
    18→
    19→class FuseOpRegistry:
    20→
    21→    def __init__(self) -> None:
    22→        self._ops: list[tuple[str, FuseOp]] = []
    23→        self._default: FuseOp = FUSE_OPS["default"]
    24→
    25→    def register(self, pattern: str, op: FuseOp) -> None:
    26→        self._ops.append((pattern, op))
    27→
    28→    def set_default(self, op: FuseOp) -> None:
    29→        self._default = op
    30→
    31→    def resolve(self,
    32→                path: str,
    33→                size: int,
    34→                ws: Workspace | None = None) -> FuseOp:
    35→        basename = path.rsplit("/", 1)[-1] if "/" in path else path
    36→        for pattern, op in self._ops:
    37→            if fnmatch.fnmatch(basename, pattern):
    38→                return op
    39→        if ws is not None:
    40→            try:
    41→                backend, _, _ = ws._registry.resolve(path)
    42→                backend_name = type(backend).__name__
    43→                op_key = _BACKEND_OP_MAP.get(backend_name)
    44→                if op_key and op_key in FUSE_OPS:
    45→                    return FUSE_OPS[op_key]
    46→            except (ValueError, FileNotFoundError):
    47→                pass
    48→        return self._default
    49→
    50→    def list_ops(self) -> list[dict]:
    51→        ops = [{"pattern": p, "name": o.name} for p, o in self._ops]
    52→        ops.append({"pattern": "*", "name": self._default.name})
    53→        return ops
    54→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


     1→from __future__ import annotations
     2→
     3→from typing import TYPE_CHECKING
     4→
     5→from mirage.fuse.base import FuseOp
     6→
     7→if TYPE_CHECKING:
     8→    from mirage.workspace import Workspace
     9→
    10→_LARGE_CSV_THRESHOLD = 50 * 1024  # 50KB
    11→_MAX_PREVIEW_ROWS = 20
    12→
    13→
    14→class CsvFuseOp(FuseOp):
    15→
    16→    name = "csv"
    17→
    18→    def on_open(self, ws: Workspace, path: str, size: int) -> dict:
    19→        return {"eager": True, "virtual": size > _LARGE_CSV_THRESHOLD}
    20→
    21→    def read(self, ws: Workspace, path: str, offset: int, size: int,
    22→             ctx: dict) -> bytes:
    23→        if "data" not in ctx:
    24→            raw = ws.cat(path)
    25→            if ctx.get("virtual"):
    26→                ctx["data"] = self._render_preview(raw, path)
    27→            else:
    28→                ctx["data"] = raw
    29→        return ctx["data"][offset:offset + size]
    30→
    31→    def _render_preview(self, raw: bytes, path: str) -> bytes:
    32→        text = raw.decode(errors="replace")
    33→        lines = text.splitlines()
    34→        total = len(lines)
    35→        header = lines[0] if lines else ""
    36→        preview_lines = lines[:_MAX_PREVIEW_ROWS + 1]
    37→        cols = len(header.split(",")) if header else 0
    38→        remaining = total - _MAX_PREVIEW_ROWS - 1
    39→        result = [
    40→            f"# CSV: {path}",
    41→            f"# {total} rows, {cols} columns",
    42→            "",
    43→            "\n".join(preview_lines),
    44→            "",
    45→            f"# ... ({remaining} more rows)",
    46→            "",
    47→        ]
    48→        return "\n".join(result).encode()
    49→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


     1→from __future__ import annotations
     2→
     3→import hashlib
     4→from typing import TYPE_CHECKING
     5→
     6→from mirage.fuse.base import FuseOp
     7→
     8→if TYPE_CHECKING:
     9→    from mirage.workspace import Workspace
    10→
    11→
    12→class RemoteFuseOp(FuseOp):
    13→
    14→    name: str = "remote"
    15→
    16→    def __init__(self, client: object) -> None:
    17→        self._client = client
    18→
    19→    def on_open(self, ws: Workspace, path: str, size: int) -> dict:
    20→        data = ws.cat(path) if size > 0 else b""
    21→        checksum = hashlib.md5(data).hexdigest()
    22→        return self._client.on_open(path=path,
    23→                                    size=size,
    24→                                    data=data,
    25→                                    checksum=checksum)
    26→
    27→    def read(self, ws: Workspace, path: str, offset: int, size: int,
    28→             ctx: dict) -> bytes:
    29→        return self._client.read(path=path, offset=offset, size=size, ctx=ctx)
    30→
    31→    def write(self, ws: Workspace, path: str, offset: int, data: bytes,
    32→              ctx: dict) -> int:
    33→        return self._client.write(path=path, offset=offset, data=data, ctx=ctx)
    34→
    35→    def on_flush(self, ws: Workspace, path: str, ctx: dict) -> None:
    36→        result = self._client.on_flush(path=path, ctx=ctx)
    37→        if result is not None:
    38→            ws.write(path, result)
    39→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


     1→import os
     2→import shlex
     3→import uuid
     4→
     5→from mirage.commands import _resolve
     6→from mirage.commands.builtin import nav
     7→from mirage.commands.custom.registry import CommandRegistry
     8→from mirage.fuse.registry import FuseOpRegistry
     9→from mirage.runtime.accessors.base import (CommandsAccessor, FuseOpsAccessor,
    10→                                           WorkspaceOpsAccessor)
    11→from mirage.runtime.accessors.local import (LocalCommandsAccessor,
    12→                                            LocalFuseOpsAccessor,
    13→                                            LocalWorkspaceOpsAccessor)
    14→from mirage.workspace import Workspace
    15→
    16→_ENV_AGENT_ID = "MIRAGE_AGENT_ID"
    17→
    18→_BLOCKED = {
    19→    "python",
    20→    "python3",
    21→    "node",
    22→    "npm",
    23→    "npx",
    24→    "ruby",
    25→    "perl",
    26→    "php",
    27→    "bash",
    28→    "sh",
    29→    "zsh",
    30→    "fish",
    31→    "exec",
    32→    "eval",
    33→    "source",
    34→    "docker",
    35→    "kubectl",
    36→    "terraform",
    37→    "ansible",
    38→    "git",
    39→    "svn",
    40→    "ssh",
    41→    "scp",
    42→    "sftp",
    43→    "rsync",
    44→    "sudo",
    45→    "su",
    46→    "chmod",
    47→    "chown",
    48→    "kill",
    49→    "ps",
    50→}
    51→
    52→
    53→class CommandNotAllowedError(Exception):
    54→    pass
    55→
    56→
    57→class Runtime:
    58→
    59→    def __init__(self,
    60→                 workspace: Workspace,
    61→                 registry: CommandRegistry | None = None,
    62→                 agent_id: str | None = None) -> None:
    63→        self.ws = workspace
    64→        self._registry = registry or CommandRegistry()
    65→        self._cwd = "/"
    66→        self.agent_id = (agent_id or os.environ.get(_ENV_AGENT_ID)
    67→                         or f"agent-{uuid.uuid4().hex[:8]}")
    68→        self.commands: CommandsAccessor = LocalCommandsAccessor(self._registry)
    69→        self.fuse_ops: FuseOpsAccessor = LocalFuseOpsAccessor(FuseOpRegistry())
    70→        self.workspace: WorkspaceOpsAccessor = LocalWorkspaceOpsAccessor(
    71→            workspace)
    72→
    73→    def run(self, command: str) -> str:
    74→        parts = shlex.split(command)
    75→        if not parts:
    76→            return ""
    77→        cmd, argv = parts[0], parts[1:]
    78→        if cmd in _BLOCKED:
    79→            raise CommandNotAllowedError(f"{cmd!r} is not allowed in Runtime.")
    80→        if cmd == "cd":

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


     1→from fastapi import FastAPI
     2→
     3→from mirage.observe.fastapi.router import observe_router
     4→from mirage.server.fastapi.routers.command_router import command_router
     5→from mirage.server.fastapi.routers.io_router import io_router
     6→from mirage.server.fastapi.routers.workspace_router import workspace_router
     7→from mirage.server.service.local import LocalService
     8→
     9→app = FastAPI(title="Mirage Server")
    10→service = LocalService()
    11→app.state.service = service
    12→
    13→app.include_router(workspace_router)
    14→app.include_router(command_router)
    15→app.include_router(io_router)
    16→app.include_router(observe_router)
    17→
    18→_sessions = service._sessions
    19→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


     1→import os
     2→import signal
     3→import subprocess
     4→import sys
     5→import time
     6→import uuid
     7→from datetime import datetime, timezone
     8→
     9→from pydantic import BaseModel, ConfigDict, Field
    10→
    11→from mirage.backend.loader import load_backend_class
    12→from mirage.cli.config import parse_mount_uri, split_mount_spec
    13→from mirage.commands import COMMANDS, _resolve
    14→from mirage.commands.builtin import nav
    15→from mirage.commands.custom.registry import CommandRegistry, ExternalCommand
    16→from mirage.fuse import FUSE_OPS
    17→from mirage.fuse.loader import build_registry_from_config, load_fuse_op_class
    18→from mirage.fuse.registry import FuseOpRegistry
    19→from mirage.observe.entries import (CommandEntry, CommandResult, DispatchInfo,
    20→                                    ParsedCommand, SessionEntry, WorkspaceInfo)
    21→from mirage.observe.session_log import get_or_create_log
    22→from mirage.runtime.base import _BLOCKED, CommandNotAllowedError
    23→from mirage.server.service.base import MirageService
    24→from mirage.server.service.cache import FileCache
    25→from mirage.types import (CommandStats, FileStat, MountMode, RuntimeType,
    26→                          SyncPolicy)
    27→from mirage.workspace import Workspace
    28→from mirage.workspace.consistency import ConsistencyPolicy
    29→
    30→
    31→class WorkspaceSession(BaseModel):
    32→    model_config = ConfigDict(arbitrary_types_allowed=True)
    33→
    34→    id: str
    35→    ws: Workspace | None
    36→    registry: CommandRegistry | None
    37→    cwd: str = "/"
    38→    fuse_mounted: bool = False
    39→    mode: MountMode = MountMode.WRITE
    40→    mountpoint: str | None = None
    41→    pid: int | None = None
    42→    mounts: list[dict] = Field(default_factory=list)
    43→    runtime_type: RuntimeType | None = None
    44→    fuse_registry: FuseOpRegistry = Field(default_factory=FuseOpRegistry)
    45→    command_stats: CommandStats = Field(default_factory=CommandStats)
    46→    created_at: float = Field(default_factory=time.monotonic)
    47→    reported_status: dict | None = None
    48→    reported_transfers: dict | None = None
    49→
    50→
    51→def _unmount_fuse(mountpoint: str, pid: int | None) -> None:
    52→    if sys.platform == "darwin":
    53→        subprocess.run(["diskutil", "unmount", "force", mountpoint],
    54→                       capture_output=True)
    55→    else:
    56→        subprocess.run(["fusermount", "-u", mountpoint], capture_output=True)
    57→    if pid:
    58→        try:
    59→            os.kill(pid, signal.SIGTERM)
    60→        except ProcessLookupError:
    61→            pass
    62→
    63→
    64→class LocalService(MirageService):
    65→
    66→    def __init__(self) -> None:
    67→        self._sessions: dict[str, WorkspaceSession] = {}
    68→        self._file_cache = FileCache()
    69→
    70→    def _get_session(self, ws_id: str) -> WorkspaceSession:
    71→        session = self._sessions.get(ws_id)
    72→        if session is None:
    73→            raise KeyError(f"workspace {ws_id!r} not found")
    74→        if session.fuse_mounted:
    75→            raise ValueError("not supported for fuse workspaces")
    76→        return session
    77→
    78→    def create_workspace(self, config: dict) -> str:
    79→        mode = config.get("mode", "write")
    80→        consistency = config.get("consistency", "cached")

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


     1→import typer
     2→
     3→from mirage.cli.commands import server, workspace
     4→from mirage.cli.commands.command import command_app, command_server_app
     5→from mirage.cli.commands.observe import observe_app
     6→
     7→app = typer.Typer(name="mirage",
     8→                  help="Mirage — unified remote filesystem CLI",
     9→                  no_args_is_help=True)
    10→
    11→app.command()(server.serve)
    12→app.command(name="quit")(server.quit_cmd)
    13→app.command()(workspace.mount)
    14→app.command(name="exec")(workspace.exec_cmd)
    15→app.command()(workspace.kill)
    16→app.command()(workspace.sync)
    17→app.command()(workspace.status)
    18→
    19→app.add_typer(workspace.workspace_app, name="workspace")
    20→app.add_typer(command_app, name="command")
    21→app.add_typer(command_server_app, name="command-server")
    22→app.add_typer(observe_app, name="observe")
    23→
    24→
    25→def main() -> None:
    26→    app()
    27→
    28→
    29→if __name__ == "__main__":
    30→    main()
    31→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


     1→import os
     2→import sys
     3→import threading
     4→import time
     5→from pathlib import Path
     6→from typing import Annotated
     7→
     8→import typer
     9→
    10→from mirage.backend.loader import load_backend_class
    11→from mirage.backend.network.proxy import ProxyBackend
    12→from mirage.cli.client import ClientError, MirageClient
    13→from mirage.cli.config import (load_workspace_yaml, parse_mount_uri,
    14→                               parse_mount_uri_full, split_mount_spec)
    15→from mirage.cli.helpers import _client, _ensure_server
    16→from mirage.fuse.fs import MirageFS
    17→from mirage.fuse.loader import build_registry_from_config
    18→from mirage.fuse.mount import mount as fuse_mount_fn
    19→from mirage.fuse.registry import FuseOpRegistry
    20→from mirage.fuse.remote.remote import RemoteFuseOp
    21→from mirage.observe.inspector import (workspace_status_from_ws,
    22→                                      workspace_transfers_from_ws)
    23→from mirage.types import MountMode, RuntimeType
    24→from mirage.workspace import Workspace
    25→from mirage.workspace.consistency import ConsistencyPolicy
    26→
    27→workspace_app = typer.Typer(no_args_is_help=True)
    28→
    29→REPORT_INTERVAL = 2
    30→
    31→
    32→def _report_loop(ws: Workspace, mountpoint: str, fs: MirageFS) -> None:
    33→    client = MirageClient()
    34→    time.sleep(2)
    35→    while True:
    36→        try:
    37→            status = workspace_status_from_ws(ws)
    38→            transfers = workspace_transfers_from_ws(ws)
    39→            ops = fs.drain_ops()
    40→            client.report_fuse_stats(mountpoint, status, transfers, ops)
    41→        except Exception:
    42→            pass
    43→        time.sleep(REPORT_INTERVAL)
    44→
    45→
    46→def _parse_mounts_for_fuse(
    47→    specs: list[str],
    48→    cfg: dict,
    49→    default_mode: MountMode,
    50→    default_consistency: ConsistencyPolicy,
    51→    ttl: int,
    52→    agent_id: str | None,
    53→) -> tuple[dict, MountMode, ConsistencyPolicy, int, str | None]:
    54→    resolved_agent_id = agent_id
    55→    mounts: dict = {}
    56→    if cfg:
    57→        if "consistency" in cfg:
    58→            default_consistency = ConsistencyPolicy(cfg["consistency"])
    59→        if "ttl" in cfg:
    60→            ttl = cfg["ttl"]
    61→        if not resolved_agent_id and "agent_id" in cfg:
    62→            resolved_agent_id = cfg["agent_id"]
    63→        for prefix, value in cfg.get("mounts", {}).items():
    64→            if isinstance(value, str):
    65→                backend_obj, m, c = parse_mount_uri_full(
    66→                    value, default_mode, default_consistency)
    67→            elif isinstance(value, dict) and "backend" in value:
    68→                cls = load_backend_class(value["backend"])
    69→                backend_obj = cls(**(value.get("args") or {}))
    70→                m = (MountMode(value["mode"])
    71→                     if "mode" in value else default_mode)
    72→                c = (ConsistencyPolicy(value["consistency"])
    73→                     if "consistency" in value else default_consistency)
    74→            elif isinstance(value, dict):
    75→                backend_obj = parse_mount_uri(value.get("uri", ""))
    76→                m = (MountMode(value["mode"])
    77→                     if "mode" in value else default_mode)
    78→                c = (ConsistencyPolicy(value["consistency"])
    79→                     if "consistency" in value else default_consistency)
    80→            else:

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


     1→import posixpath
     2→from typing import Callable
     3→
     4→from mirage.types import CostLevel
     5→from mirage.workspace import Workspace
     6→
     7→from . import nav, net, read, search, write
     8→
     9→
    10→def _resolve(cwd: str, path: str) -> str:
    11→    if path.startswith("/"):
    12→        return path
    13→    return posixpath.normpath(posixpath.join(cwd, path))
    14→
    15→
    16→def _check_flags(cmd: str, argv: list[str], allowed: set[str]) -> None:
    17→    for a in argv:
    18→        if not a.startswith("-") or a in (">", ">>", "--"):
    19→            continue
    20→        if a.startswith("--"):
    21→            if a not in allowed:
    22→                raise ValueError(f"{cmd}: unrecognized option '{a}'")
    23→            continue
    24→        if a in allowed:
    25→            continue
    26→        for ch in a[1:]:
    27→            if not ch.isalpha():
    28→                break
    29→            if f"-{ch}" not in allowed:
    30→                raise ValueError(f"{cmd}: invalid option -- '{ch}'")
    31→
    32→
    33→def _ls(ws: Workspace, argv: list[str], cwd: str) -> str:
    34→    _check_flags("ls", argv,
    35→                 {"-l", "-a", "-A", "-h", "-t", "-S", "-r", "-1", "-R", "-d"})
    36→    long = any(
    37→        a.startswith("-") and not a.startswith("--") and "l" in a
    38→        for a in argv)
    39→    all_files = any(
    40→        a.startswith("-") and not a.startswith("--") and ("a" in a or "A" in a)
    41→        for a in argv)
    42→    human_readable = any(
    43→        a.startswith("-") and not a.startswith("--") and "h" in a
    44→        for a in argv)
    45→    reverse = any(
    46→        a.startswith("-") and not a.startswith("--") and "r" in a
    47→        for a in argv)
    48→    recursive = any(
    49→        a.startswith("-") and not a.startswith("--") and "R" in a
    50→        for a in argv)
    51→    list_dir = any(
    52→        a.startswith("-") and not a.startswith("--") and "d" in a
    53→        for a in argv)
    54→    sort_by = "name"
    55→    for a in argv:
    56→        if a.startswith("-") and not a.startswith("--"):
    57→            if "t" in a:
    58→                sort_by = "time"
    59→            elif "S" in a:
    60→                sort_by = "size"
    61→    paths = [a for a in argv if not a.startswith("-")] or [cwd]
    62→    results: list[str] = []
    63→    for p in paths:
    64→        entries = nav.ls(ws,
    65→                         _resolve(cwd, p),
    66→                         long=long,
    67→                         all_files=all_files,
    68→                         sort_by=sort_by,
    69→                         reverse=reverse,
    70→                         human_readable=human_readable,
    71→                         recursive=recursive,
    72→                         list_dir=list_dir)
    73→        if long:
    74→            for e in entries:
    75→                size_str = nav._human_size(
    76→                    e.size or 0) if human_readable else str(e.size or 0)
    77→                line = (f"{e.type or '-'}\t{size_str}"
    78→                        f"\t{e.modified or ''}\t{e.name}")
    79→                results.append(line)
    80→        else:

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


     1→from mirage.commands.builtin.handlers import COMMAND_COST, COMMANDS, _resolve
     2→
     3→__all__ = ["COMMANDS", "COMMAND_COST", "_resolve"]
     4→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


     1→import hashlib
     2→import shlex
     3→from typing import TYPE_CHECKING
     4→
     5→from pydantic import BaseModel, ConfigDict
     6→
     7→from mirage.commands import COMMANDS
     8→from mirage.commands.custom.arg_resolver import classify_args
     9→from mirage.commands.custom.executor import run_backend_method, run_external
    10→from mirage.server.constants import _parse_size
    11→from mirage.types import FilePayload, RemoteCommandOptions
    12→from mirage.workspace import Workspace
    13→
    14→if TYPE_CHECKING:
    15→    from mirage.commands.remote.client import CommandClient
    16→
    17→
    18→class ExternalCommand(BaseModel):
    19→    model_config = ConfigDict(frozen=True)
    20→
    21→    name: str
    22→    exec: str
    23→    description: str = ""
    24→    options: RemoteCommandOptions = RemoteCommandOptions()
    25→
    26→
    27→def _is_local_path(exec_str: str) -> bool:
    28→    first = shlex.split(exec_str)[0] if exec_str.strip() else ""
    29→    return first.startswith("/") or first.startswith("./")
    30→
    31→
    32→def _md5(data: bytes) -> str:
    33→    return hashlib.md5(data).hexdigest()
    34→
    35→
    36→class CommandRegistry:
    37→
    38→    def __init__(self, client: "CommandClient | None" = None) -> None:
    39→        self._external: dict[str, ExternalCommand] = {}
    40→        self._client = client
    41→
    42→    def register(self, cmd: ExternalCommand) -> None:
    43→        self._external[cmd.name] = cmd
    44→
    45→    def list_commands(self) -> list[str]:
    46→        return sorted(list(COMMANDS.keys()) + list(self._external.keys()))
    47→
    48→    def run(self,
    49→            ws: Workspace,
    50→            command: str,
    51→            cwd: str = "/",
    52→            stdin: bytes | None = None) -> str:
    53→        parts = shlex.split(command)
    54→        if not parts:
    55→            return ""
    56→        cmd_name, argv = parts[0], parts[1:]
    57→
    58→        if cmd_name in self._external:
    59→            ext = self._external[cmd_name]
    60→            if _is_local_path(ext.exec):
    61→                return run_external(ws, ext, argv, cwd)
    62→            if self._client is not None:
    63→                return self._dispatch_to_client(ws, ext, cmd_name, argv, cwd,
    64→                                                stdin)
    65→            return run_external(ws, ext, argv, cwd)
    66→
    67→        if cmd_name in COMMANDS:
    68→            return COMMANDS[cmd_name](ws, argv, cwd)
    69→
    70→        return run_backend_method(ws, cmd_name, argv, cwd)
    71→
    72→    def _dispatch_to_client(self, ws: Workspace, ext: ExternalCommand,
    73→                            cmd_name: str, argv: list[str], cwd: str,
    74→                            stdin: bytes | None) -> str:
    75→        classified = classify_args(ws, argv, cwd)
    76→        max_size = _parse_size(ext.options.max_file_size)
    77→
    78→        for vp in classified.potential_outputs:
    79→            ws._assert_writable(vp)
    80→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


     1→import fcntl
     2→import json
     3→import os
     4→import uuid
     5→from datetime import datetime, timezone
     6→from pathlib import Path
     7→
     8→from mirage.observe.entries import CommandEntry, SessionEntry
     9→
    10→
    11→class SessionLog:
    12→
    13→    def __init__(self, ws_id: str, base_dir: str | None = None) -> None:
    14→        self._ws_id = ws_id
    15→        self._base = Path(base_dir or os.path.expanduser("~/.mirage/sessions"))
    16→        ts = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S")
    17→        uid = uuid.uuid4().hex[:8]
    18→        self._dir = self._base / ws_id
    19→        self._dir.mkdir(parents=True, exist_ok=True)
    20→        self._path = self._dir / f"{ts}_{uid}.jsonl"
    21→        self._command_seq = 0
    22→
    23→    @property
    24→    def path(self) -> Path:
    25→        return self._path
    26→
    27→    def write_session(self, entry: SessionEntry) -> None:
    28→        self._append(entry.to_dict())
    29→
    30→    def write_command(self, entry: CommandEntry) -> None:
    31→        self._command_seq += 1
    32→        if not entry.id:
    33→            entry.id = f"c{self._command_seq:03d}"
    34→        self._append(entry.to_dict())
    35→
    36→    def read_last(self, n: int = 50) -> list[dict]:
    37→        if not self._path.exists():
    38→            return []
    39→        lines = self._path.read_text().strip().splitlines()
    40→        result = []
    41→        for line in lines[-n:]:
    42→            result.append(json.loads(line))
    43→        return result
    44→
    45→    def _append(self, data: dict) -> None:
    46→        line = json.dumps(data, default=str) + "\n"
    47→        with open(self._path, "a") as f:
    48→            fcntl.flock(f.fileno(), fcntl.LOCK_EX)
    49→            f.write(line)
    50→            fcntl.flock(f.fileno(), fcntl.LOCK_UN)
    51→
    52→
    53→_session_logs: dict[str, SessionLog] = {}
    54→
    55→
    56→def get_or_create_log(ws_id: str) -> SessionLog:
    57→    if ws_id not in _session_logs:
    58→        _session_logs[ws_id] = SessionLog(ws_id)
    59→    return _session_logs[ws_id]
    60→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


     1→from mirage.runtime.base import Runtime
     2→from mirage.runtime.local import LocalRuntime
     3→from mirage.runtime.memory import MemoryRuntime
     4→from mirage.runtime.remote import RemoteRuntime
     5→
     6→__all__ = ["MemoryRuntime", "LocalRuntime", "RemoteRuntime", "Runtime"]
     7→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


     1→from mirage.observe.inspector import set_server_start_time
     2→from mirage.observe.session_log import SessionLog
     3→
     4→__all__ = ["SessionLog", "set_server_start_time"]
     5→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


     1→import time
     2→from collections import OrderedDict
     3→
     4→from mirage.workspace.cache.entry import CacheEntry
     5→
     6→
     7→def _parse_limit(limit: str | int) -> int:
     8→    if isinstance(limit, int):
     9→        return limit
    10→    s = limit.strip().upper()
    11→    for suffix, mult in [("GB", 1 << 30), ("MB", 1 << 20), ("KB", 1 << 10)]:
    12→        if s.endswith(suffix):
    13→            return int(s[:-len(suffix)]) * mult
    14→    return int(s)
    15→
    16→
    17→class LRUCache:
    18→
    19→    def __init__(self, limit: str | int = "512MB") -> None:
    20→        self._limit = _parse_limit(limit)
    21→        self._store: OrderedDict[str, CacheEntry] = OrderedDict()
    22→        self._size = 0
    23→
    24→    def get(self, path: str) -> CacheEntry | None:
    25→        if path not in self._store:
    26→            return None
    27→        self._store.move_to_end(path)
    28→        return self._store[path]
    29→
    30→    def put(self,
    31→            path: str,
    32→            data: bytes,
    33→            etag: str | None = None,
    34→            modified: str | None = None,
    35→            size: int | None = None) -> None:
    36→        if path in self._store:
    37→            self._size -= len(self._store[path].data)
    38→            del self._store[path]
    39→        self._store[path] = CacheEntry(
    40→            data=data,
    41→            cached_at=time.monotonic(),
    42→            etag=etag,
    43→            modified=modified,
    44→            size=size,
    45→        )
    46→        self._size += len(data)
    47→        self._evict()
    48→
    49→    def invalidate(self, path: str) -> None:
    50→        if path in self._store:
    51→            self._size -= len(self._store[path].data)
    52→            del self._store[path]
    53→
    54→    def clear(self) -> None:
    55→        self._store.clear()
    56→        self._size = 0
    57→
    58→    @property
    59→    def size(self) -> int:
    60→        return self._size

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


     1→from pydantic import BaseModel
     2→
     3→
     4→class CacheEntry(BaseModel):
     5→    data: bytes
     6→    cached_at: float
     7→    etag: str | None = None
     8→    modified: str | None = None
     9→    size: int | None = None
    10→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


     1→from mirage.fuse.base import FuseOp
     2→
     3→
     4→class DefaultFuseOp(FuseOp):
     5→
     6→    name = "default"
     7→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>


     1→import base64
     2→
     3→from fastapi import APIRouter, HTTPException, Request
     4→
     5→from mirage.server import routes
     6→from mirage.server.fastapi.config import (PathRequest, ReaddirRequest,
     7→                                          ReadRequest, RenameRequest,
     8→                                          TruncateRequest, WriteRequest)
     9→
    10→io_router = APIRouter(tags=["io"])
    11→
    12→
    13→def _get_service(request: Request):
    14→    return request.app.state.service
    15→
    16→
    17→@io_router.post(routes.IO_READ)
    18→def io_read(ws_id: str, req: ReadRequest, request: Request) -> dict:
    19→    svc = _get_service(request)
    20→    try:
    21→        data = svc.io_read(ws_id, req.path, req.offset, req.size)
    22→    except KeyError:
    23→        raise HTTPException(status_code=404, detail="workspace not found")
    24→    except FileNotFoundError:
    25→        raise HTTPException(status_code=404, detail="file not found")
    26→    return {"data": base64.b64encode(data).decode()}
    27→
    28→
    29→@io_router.post(routes.IO_WRITE)
    30→def io_write(ws_id: str, req: WriteRequest, request: Request) -> dict:
    31→    svc = _get_service(request)
    32→    try:
    33→        raw = base64.b64decode(req.data)
    34→        written = svc.io_write(ws_id, req.path, req.offset, raw)
    35→    except KeyError:
    36→        raise HTTPException(status_code=404, detail="workspace not found")
    37→    except FileNotFoundError:
    38→        raise HTTPException(status_code=404, detail="file not found")
    39→    return {"written": written}
    40→
    41→
    42→@io_router.post(routes.IO_STAT)
    43→def io_stat(ws_id: str, req: PathRequest, request: Request) -> dict:
    44→    svc = _get_service(request)
    45→    try:
    46→        st = svc.io_stat(ws_id, req.path)
    47→    except KeyError:
    48→        raise HTTPException(status_code=404, detail="workspace not found")
    49→    except FileNotFoundError:
    50→        raise HTTPException(status_code=404, detail="file not found")
    51→    return st.model_dump()
    52→
    53→
    54→@io_router.post(routes.IO_READDIR)
    55→def io_readdir(ws_id: str, req: ReaddirRequest, request: Request) -> dict:
    56→    svc = _get_service(request)
    57→    try:
    58→        entries, cursor = svc.io_readdir(ws_id, req.path, req.cursor)
    59→    except KeyError:
    60→        raise HTTPException(status_code=404, detail="workspace not found")
    61→    return {"entries": entries, "cursor": cursor}
    62→
    63→
    64→@io_router.post(routes.IO_CREATE)
    65→def io_create(ws_id: str, req: PathRequest, request: Request) -> dict:
    66→    svc = _get_service(request)
    67→    try:
    68→        svc.io_create(ws_id, req.path)
    69→    except KeyError:
    70→        raise HTTPException(status_code=404, detail="workspace not found")
    71→    return {"ok": True}
    72→
    73→
    74→@io_router.post(routes.IO_UNLINK)
    75→def io_unlink(ws_id: str, req: PathRequest, request: Request) -> dict:
    76→    svc = _get_service(request)
    77→    try:
    78→        svc.io_unlink(ws_id, req.path)
    79→    except KeyError:
    80→        raise HTTPException(status_code=404, detail="workspace not found")

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>