file_safety.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. """Shared file safety rules used by both tools and ACP shims.
  2. Every guard here is defense-in-depth, NOT a security boundary: the terminal
  3. tool runs as the same OS user and can read/write anything. The value is a
  4. clear denial for models that respect tool errors plus a visible audit trail.
  5. """
  6. from __future__ import annotations
  7. import os
  8. from pathlib import Path
  9. from contextlib import suppress
  10. from typing import Optional
  11. from hermes_cli.home_data_layout import SECRET_CACHE_STORES
  12. def _constants_path(getter_name: str) -> Path:
  13. """Call ``hermes_constants.<getter_name>()`` (local import avoids cycles); ``~/.hermes`` on any failure."""
  14. try:
  15. import hermes_constants
  16. return getattr(hermes_constants, getter_name)()
  17. except Exception:
  18. return Path(os.path.expanduser("~/.hermes"))
  19. def _hermes_home_path() -> Path:
  20. """Active HERMES_HOME (profile-aware). Tests monkeypatch this name."""
  21. return _constants_path("get_hermes_home")
  22. def _hermes_root_path() -> Path:
  23. """Hermes root dir (parent of any profile, never per-profile)."""
  24. return _constants_path("get_default_hermes_root")
  25. def _hermes_dirs() -> list[Path]:
  26. """Resolved active HERMES_HOME and global root, deduplicated.
  27. Both are checked so credential stores at <root>/... stay guarded when
  28. running under a profile (HERMES_HOME = <root>/profiles/<name>).
  29. """
  30. return list(dict.fromkeys(_resolve_each((_hermes_home_path(), _hermes_root_path()))))
  31. def _resolve_each(paths) -> list[Path]:
  32. """``p.resolve()`` for each path, skipping ones that fail to resolve."""
  33. out: list[Path] = []
  34. for p in paths:
  35. with suppress(Exception):
  36. out.append(p.resolve())
  37. return out
  38. def _is_under(resolved: str | Path, base: str | Path) -> bool:
  39. """True when ``resolved`` equals ``base`` or lies below it (both already resolved);
  40. ``Path`` inputs use ``relative_to`` (platform semantics), ``str`` a realpath prefix test."""
  41. if isinstance(resolved, Path):
  42. try:
  43. return resolved.relative_to(base) is not None
  44. except ValueError:
  45. return False
  46. return resolved == base or resolved.startswith(str(base) + os.sep)
  47. def _resolve_target(path: str) -> Optional[Path]:
  48. """``Path(expanduser(path)).resolve()``, or None when resolution fails."""
  49. with suppress(OSError, RuntimeError):
  50. return Path(os.path.expanduser(str(path))).resolve()
  51. return None
  52. def _guard_homes(path: str = "") -> set[str]:
  53. """Every home the write guards must cover. Process ``~`` alone is wrong whenever the
  54. process HOME is not the OS user's real home — ``TERMINAL_HOME_MODE=profile``,
  55. containers, and spawned workers pin ``HOME`` to ``{HERMES_HOME}/home``, which leaves
  56. the real home's credential paths unguarded against absolute-path writes while file
  57. tools happily write there (and ``_expand_tilde`` may route ``~`` to yet another
  58. home). Deny/approval lists are built over the union: process home, real home,
  59. subprocess home, and the profile home. A ``~name/...`` input resolves to a named
  60. account's home, which joins the set so ``~root/.ssh/authorized_keys`` stays denied."""
  61. homes = {os.path.expanduser("~")}
  62. with suppress(Exception):
  63. from hermes_constants import get_real_home, get_subprocess_home, _profile_home_path
  64. for candidate in (get_real_home(), get_subprocess_home(), _profile_home_path()):
  65. if candidate:
  66. homes.add(str(candidate))
  67. raw = str(path)
  68. if len(raw) > 1 and raw.startswith("~") and raw[1] not in "/\\":
  69. name = raw[1:].split("/", 1)[0].split("\\", 1)[0]
  70. expanded = os.path.expanduser(f"~{name}")
  71. if not expanded.startswith("~"):
  72. homes.add(expanded)
  73. return {os.path.realpath(h) for h in homes}
  74. def _homes_and_resolved(path: str) -> tuple[set[str], str]:
  75. """``(guard homes, realpath(expanduser(path)))`` — the write-guard coordinate pair."""
  76. return _guard_homes(path), os.path.realpath(os.path.expanduser(str(path)))
  77. # ---------------------------------------------------------------------------
  78. # Windows NT-namespace path guard
  79. #
  80. # Pre-approval file accesses reject Windows NT-namespace (``\??\``) paths so
  81. # the remaining unguarded path touches cannot be turned into an NTLM
  82. # credential leak.
  83. #
  84. # The vector: on Windows, merely *resolving or touching* a path such as
  85. # ``\\??\\UNC\\attacker.example\\share\\x`` (or the ``\\\\?\\UNC\\`` /
  86. # ``GLOBALROOT`` re-entry forms) makes the OS initiate SMB authentication to
  87. # the remote host, leaking the user's NTLM hash — even when the read itself
  88. # fails or would later be denied. NT object-namespace paths also bypass
  89. # normal Win32 path normalization, which lets them dodge deny-prefix checks
  90. # built on ``realpath()`` string comparison. A model tricked by injected
  91. # content into "reading" such a path leaks credentials before any denylist
  92. # built on resolved paths can fire.
  93. #
  94. # Consequently this check MUST run on the *raw* path string before any
  95. # ``Path.resolve()`` / ``os.path.realpath()`` call, and it does — it is the
  96. # first check in both :func:`get_read_block_error` and the write-denial
  97. # classifier.
  98. #
  99. # Scope (deliberately narrow to avoid false positives):
  100. # * ``\\??\\...`` — NT object-namespace paths. Never legitimate
  101. # tool input on any platform.
  102. # * ``\\\\.\\...`` — Win32 device namespace (``\\\\.\\pipe\\``,
  103. # ``\\\\.\\PhysicalDrive0``, ...). Not a file
  104. # read/write target for agent tools.
  105. # * ``\\\\?\\UNC\\...`` — extended-length UNC form (remote host).
  106. # * ``\\\\?\\GLOBALROOT...`` — re-entry into the NT namespace.
  107. #
  108. # Plain drive-letter extended-length paths (``\\\\?\\C:\\...``) stay ALLOWED:
  109. # they are a routine local form (see hermes_cli/windows_ssh_runtime.py) and
  110. # carry no remote-auth trigger. Plain UNC shares (``\\\\server\\share``) are
  111. # also unchanged here — blocking ordinary UNC reads is a policy question,
  112. # not part of this namespace-bypass guard.
  113. #
  114. # The guard runs on every platform: these prefixes are never legitimate
  115. # inputs on POSIX either, and path strings can be relayed toward Windows
  116. # hosts (remote terminal backends, desktop bridges).
  117. # ---------------------------------------------------------------------------
  118. def is_nt_namespace_path(path: str) -> bool:
  119. """Return True if ``path`` is a Windows NT-/device-namespace path.
  120. Checks the raw string only — never resolves the path (resolving is the
  121. credential-leak trigger this guard exists to prevent).
  122. """
  123. s = str(path).replace("/", "\\")
  124. if s.startswith("\\??\\"):
  125. return True
  126. if s.startswith("\\\\.\\"):
  127. return True
  128. if s.startswith("\\\\?\\"):
  129. rest = s[4:]
  130. upper = rest.upper()
  131. if upper.startswith("UNC\\") or upper.startswith("GLOBALROOT\\"):
  132. return True
  133. return False
  134. def get_nt_namespace_error(path: str, *, verb: str = "Access") -> Optional[str]:
  135. """Return an error message when ``path`` uses the NT/device namespace."""
  136. if not is_nt_namespace_path(path):
  137. return None
  138. return (
  139. f"{verb} denied: '{path}' uses a Windows NT/device namespace prefix "
  140. "(\\??\\, \\\\.\\, \\\\?\\UNC\\, or GLOBALROOT). These paths bypass "
  141. "normal path normalization and can trigger outbound SMB "
  142. "authentication (NTLM credential leak) merely by being resolved. "
  143. "Use a normal absolute path instead."
  144. )
  145. def build_write_denied_paths(home: str) -> set[str]:
  146. """Return exact sensitive paths that must never be written."""
  147. # ``~/.ssh/config`` is deliberately NOT hard-denied: no key bytes, and editing
  148. # it is routine. It can carry ProxyCommand / Match exec, so it goes through the
  149. # approval gate instead (build_write_approval_paths).
  150. home_files = (
  151. (".ssh", "authorized_keys"), (".ssh", "id_rsa"), (".ssh", "id_ed25519"),
  152. (".netrc",), (".pgpass",), (".npmrc",), (".pypirc",), (".git-credentials",),
  153. )
  154. # Secret material under HERMES_HOME, on both the active profile and the global
  155. # root: overwriting the root .env leaks credentials across every profile that
  156. # inherits it, and the root Anthropic PKCE store is still read by default /
  157. # non-profile sessions when a profile is active. google_oauth.json is an OAuth
  158. # token store; SECRET_CACHE_STORES hold secret values and the Photon sidecar token.
  159. #
  160. # auth.json, auth.lock, config.yaml and webhook_subscriptions.json are
  161. # deliberately NOT here: #45947 freed those control files on purpose
  162. # ("true containment belongs in Docker/remote backends and OS permissions,
  163. # not an expanding hardcoded denylist"). They stay read-denied, not write-denied.
  164. hermes_files = (
  165. ".env", ".anthropic_oauth.json",
  166. os.path.join("auth", "google_oauth.json"),
  167. *SECRET_CACHE_STORES,
  168. )
  169. paths = [
  170. *(os.path.join(home, *f) for f in home_files),
  171. *(str(base / f) for f in hermes_files for base in (_hermes_home_path(), _hermes_root_path())),
  172. "/etc/sudoers", "/etc/passwd", "/etc/shadow",
  173. ]
  174. return {os.path.realpath(p) for p in paths}
  175. # Home-relative credential directories (POSIX paths). Also dropped from profile exports (hermes_cli.profiles).
  176. HOME_CREDENTIAL_DIRS = (".ssh", ".aws", ".gnupg", ".kube", ".docker", ".azure", ".config/gh", ".config/gcloud")
  177. def build_write_denied_prefixes(home: str) -> list[str]:
  178. """Return sensitive directory prefixes that must never be written."""
  179. paths = [
  180. *(os.path.join(home, *d.split("/")) for d in HOME_CREDENTIAL_DIRS),
  181. "/etc/sudoers.d", "/etc/systemd",
  182. ]
  183. return [os.path.realpath(p) + os.sep for p in paths]
  184. def get_safe_write_roots() -> set[str]:
  185. """Resolved HERMES_WRITE_SAFE_ROOT paths (``os.pathsep``-separated list)."""
  186. roots: set[str] = set()
  187. for path in filter(None, os.getenv("HERMES_WRITE_SAFE_ROOT", "").split(os.pathsep)):
  188. with suppress(OSError, ValueError):
  189. roots.add(os.path.realpath(os.path.expanduser(path)))
  190. return roots
  191. def build_write_approval_paths(home: str) -> set[str]:
  192. """Paths that need human APPROVAL to write but are not hard-denied credentials.
  193. ``~/.ssh/config`` is routine to edit and holds no key bytes, but can carry
  194. ``ProxyCommand`` / ``Match exec``. Interactive file tools prompt
  195. (approve-once/session/always, like the terminal tool's ``~/.ssh`` gate);
  196. non-interactive callers (ACP shims, background jobs) fail closed.
  197. """
  198. return {os.path.realpath(os.path.join(home, ".ssh", "config"))}
  199. # HERMES_HOME / root subpaths that the agent's generic file tools must not
  200. # rewrite. Session transcripts (state.db, sessions/) are application-owned
  201. # state whose rewrite can falsify history and break resume/compression;
  202. # mcp-tokens/, pairing/, vault/ (key + ciphertext side by side),
  203. # browser-profile/ (copied cookies / Login Data) and webapp/ (the Webapp's
  204. # browser credential and its grants to native apps) hold credential material.
  205. # Control files (auth.json, config.yaml, webhook_subscriptions.json) are
  206. # deliberately NOT here (#45947): read-denied, but the user may ask to edit them.
  207. _HERMES_PROTECTED_SUBPATHS = (
  208. "state.db", "sessions", "mcp-tokens", "pairing", "vault", "browser-profile", "webapp")
  209. def _classify_write_denial(path: str, *, entry: bool = False) -> Optional[str]:
  210. """Return ``'credential'``, ``'safe_root'``, ``'nt_namespace'``, or ``None`` if writes are allowed.
  211. ``entry=True`` is for ops that unlink/rename the directory entry itself (a
  212. symlink, not its target): the entry — parent realpath'd, final component
  213. kept — is vetted as well as the target it resolves to."""
  214. # NT/device-namespace check runs on the RAW string, before realpath():
  215. # resolving such a path is itself the NTLM-leak trigger, and namespace
  216. # prefixes defeat string-prefix denylist comparison after normalization.
  217. if is_nt_namespace_path(path):
  218. return "nt_namespace"
  219. homes, resolved = _homes_and_resolved(path)
  220. # The runtime's own interpreter/venv is never agent-writable (an overwrite
  221. # bricks the next start exactly like a delete, #58748) — and this must fire
  222. # BEFORE the approval-gated allow so ~/.ssh-style gating cannot re-open it.
  223. from agent.runtime_self_protection import is_protected_path, split_entry
  224. if is_protected_path(path) or (entry and is_protected_path(path, follow=False)):
  225. return "credential"
  226. denial = _classify_resolved_write_denial(homes, resolved)
  227. if denial or not entry:
  228. return denial
  229. parent, leaf = split_entry(os.path.expanduser(str(path)))
  230. entry_path = os.path.join(os.path.realpath(parent or "."), leaf)
  231. return _classify_resolved_write_denial(homes, entry_path)
  232. def _classify_resolved_write_denial(homes: set[str], resolved: str) -> Optional[str]:
  233. """Credential / protected-subpath / safe-root verdict for an already-resolved path."""
  234. # Approval-gated paths are allowed at this layer so interactive tools can
  235. # prompt; checked first so the ``.ssh/`` prefix deny doesn't swallow them.
  236. if any(resolved in build_write_approval_paths(home) for home in homes):
  237. return None
  238. if any(
  239. resolved in build_write_denied_paths(home)
  240. or any(resolved.startswith(prefix) for prefix in build_write_denied_prefixes(home))
  241. for home in homes
  242. ):
  243. return "credential"
  244. for base in _hermes_dirs():
  245. for sub in _HERMES_PROTECTED_SUBPATHS:
  246. with suppress(Exception):
  247. if _is_under(resolved, os.path.realpath(os.path.join(str(base), sub))):
  248. return "credential"
  249. safe_roots = get_safe_write_roots()
  250. if safe_roots and not any(_is_under(resolved, root) for root in safe_roots):
  251. return "safe_root"
  252. return None
  253. def is_write_denied(path: str) -> bool:
  254. """Return True if path is blocked by the write denylist or safe root."""
  255. return _classify_write_denial(path) is not None
  256. def get_write_denied_error(path: str, *, verb: str = "Write", entry: bool = False) -> Optional[str]:
  257. """Return a user/model-facing error when writes to ``path`` are blocked
  258. (``entry``: see :func:`_classify_write_denial`)."""
  259. denial = _classify_write_denial(path, entry=entry)
  260. if denial == "safe_root":
  261. roots_display = os.pathsep.join(sorted(get_safe_write_roots()))
  262. return (
  263. f"{verb} denied: '{path}' is outside HERMES_WRITE_SAFE_ROOT "
  264. f"({roots_display}). Unset the variable or add this path's directory prefix."
  265. )
  266. if denial == "nt_namespace":
  267. return get_nt_namespace_error(path, verb=verb)
  268. return f"{verb} denied: '{path}' is a protected system/credential file." if denial else None
  269. def is_write_approval_required(path: str) -> bool:
  270. """True if ``path`` is approval-gated (``~/.ssh/config``): interactive callers
  271. prompt, callers without a channel treat it as a block (fail closed)."""
  272. homes, resolved = _homes_and_resolved(path)
  273. return any(resolved in build_write_approval_paths(home) for home in homes)
  274. # Secret-bearing project-local env file basenames, blocked anywhere on disk.
  275. _BLOCKED_PROJECT_ENV_BASENAMES: set[str] = {
  276. ".env", ".env.local", ".env.development", ".env.production", ".env.test", ".env.staging", ".envrc",
  277. }
  278. _DID_SUFFIX = (
  279. " (Defense-in-depth — not a security boundary; the terminal tool can still bypass.)"
  280. )
  281. # Exact-file credential stores under HERMES_HOME / <root>. The agent never
  282. # needs these directly — provider tools consume them through internal channels.
  283. _CREDENTIAL_FILE_NAMES = (
  284. "auth.json", "auth.lock", ".anthropic_oauth.json", ".env", "webhook_subscriptions.json",
  285. os.path.join("auth", "google_oauth.json"), *SECRET_CACHE_STORES,
  286. )
  287. # Directory-prefix read denies under HERMES_HOME / <root>: (subdir, message for
  288. # the directory itself, message for a file inside). browser-profile/ is a copy
  289. # of the user's Cookies / Login Data — the same credential class as auth.json.
  290. _READ_DENIED_DIRS = (
  291. ("mcp-tokens",
  292. "is the Hermes MCP token directory and cannot be read directly.",
  293. "is a Hermes MCP token file and cannot be read directly."),
  294. ("browser-profile",
  295. "is the Hermes real-profile browser snapshot directory (copied cookies/logins) and cannot be read directly.",
  296. "is inside the Hermes real-profile browser snapshot (copied cookies/logins) and cannot be read directly."),
  297. # vault.key + vault.json.enc sit side by side; key + ciphertext = plaintext, so the whole dir is one credential.
  298. ("vault",
  299. "is the Hermes credential vault directory and cannot be read directly (secrets are filled server-side by browser_vault).",
  300. "is inside the Hermes credential vault (encrypted secrets + local key) and cannot be read directly (browser_vault resolves them server-side)."),
  301. # session-token is the Webapp's browser credential (a bare token no redaction pattern masks); the
  302. # rest are its grants to native apps and its Web Access registration.
  303. ("webapp",
  304. "is the Hermes Webapp sign-in directory and cannot be read directly.",
  305. "is a Hermes Webapp sign-in file (the browser credential or its sign-in records) and cannot be read directly."),
  306. )
  307. def get_read_block_error(path: str) -> Optional[str]:
  308. """Return an error message when a read targets a denied Hermes path.
  309. Blocked: internal skill-hub caches (prompt-injection carriers), credential
  310. stores under HERMES_HOME and the global root (exact files, plus anything
  311. under ``mcp-tokens/``, ``browser-profile/``, ``vault/`` and ``webapp/``), and project-local ``.env``
  312. files anywhere on disk (``.env.example`` is the documented-shape substitute).
  313. Callers that resolve relative paths against a non-process cwd (e.g.
  314. ``TERMINAL_CWD``) MUST pass an absolute path: ``resolve()`` here anchors at
  315. the process cwd, so a relative ``"auth.json"`` would miss the denylist.
  316. """
  317. # NT/device-namespace check runs on the RAW string, before resolve():
  318. # on Windows, resolving \??\UNC\host\share (or \\?\UNC\, GLOBALROOT)
  319. # already triggers outbound SMB auth — the NTLM leak happens before any
  320. # resolved-path denylist could fire. Namespace prefixes also bypass
  321. # normal path normalization, defeating prefix-comparison denylists.
  322. nt_error = get_nt_namespace_error(path, verb="Read")
  323. if nt_error:
  324. return nt_error
  325. resolved = Path(path).expanduser().resolve()
  326. hermes_dirs = _hermes_dirs()
  327. reason = None
  328. if any(_is_under(resolved, hd / "skills" / ".hub") for hd in hermes_dirs):
  329. reason = (
  330. "is an internal Hermes cache file and cannot be read directly to prevent "
  331. "prompt injection. Use the skills_list or skill_view tools instead."
  332. )
  333. elif any(resolved in _resolve_each(hd / name for hd in hermes_dirs) for name in _CREDENTIAL_FILE_NAMES):
  334. reason = (
  335. "is a Hermes credential store and cannot be read directly. Provider tools "
  336. "consume these credentials through internal channels." + _DID_SUFFIX
  337. )
  338. else:
  339. for subdir, dir_msg, file_msg in _READ_DENIED_DIRS:
  340. for blocked_dir in _resolve_each(hd / subdir for hd in hermes_dirs):
  341. if _is_under(resolved, blocked_dir):
  342. reason = (dir_msg if resolved == blocked_dir else file_msg) + _DID_SUFFIX
  343. break
  344. if reason:
  345. break
  346. if reason is None and resolved.name.lower() in _BLOCKED_PROJECT_ENV_BASENAMES:
  347. reason = (
  348. "is a secret-bearing environment file and cannot be read to prevent credential "
  349. "leakage. If you need to check the file structure, read .env.example instead." + _DID_SUFFIX
  350. )
  351. return f"Access denied: {path} {reason}" if reason else None
  352. def raise_if_read_blocked(path: str) -> None:
  353. """Raise ``ValueError`` if ``path`` is a denied Hermes read (see ``get_read_block_error``).
  354. Shared chokepoint for provider input-loading sites (e.g. image-gen local
  355. paths). Best-effort: unexpected internal errors no-op rather than break
  356. local-file loading; a real block still propagates.
  357. """
  358. try:
  359. blocked = get_read_block_error(path)
  360. except Exception:
  361. return
  362. if blocked:
  363. raise ValueError(blocked)
  364. def _resolve_active_profile_name() -> str:
  365. """Active profile name from HERMES_HOME: ``~/.hermes`` -> ``"default"``,
  366. ``~/.hermes/profiles/X`` -> ``"X"``; ``"default"`` on any resolution failure."""
  367. try:
  368. parts = _hermes_home_path().resolve().relative_to(_hermes_root_path().resolve() / "profiles").parts
  369. except (OSError, RuntimeError, ValueError):
  370. return "default"
  371. return parts[0] if parts else "default"
  372. # --- Sandbox-mirror write guard ---
  373. # Non-local terminal backends bind a sandbox-local dir to the container's $HOME:
  374. # <HERMES_HOME>/profiles/<name>/sandboxes/<backend>/<task>/home/.hermes/...
  375. # A host-side write there lands on a mirror the host never reads: silent success,
  376. # divergent copies. Path-shape-only detection, independent of the active profile;
  377. # the inner-container case (bind mount strips the prefix) is classify_container_mirror_target.
  378. _SANDBOX_MIRROR_WARNING = (
  379. "Sandbox-mirror write blocked by soft guard: {target_path} "
  380. "sits under {mirror_root!r}, which is {body} "
  381. "Use the host-side tool for authoritative state (e.g. ``memory`` for memories), "
  382. "or address the host path directly. To bypass {bypass} with ``cross_profile=True``. "
  383. "(Defense-in-depth — not a security boundary; the terminal tool can still bypass.)"
  384. )
  385. def _mirror_info(target: Path, mirror_root: Path, inner_path: str) -> dict:
  386. """Common ``classify_*_mirror_target`` result shape."""
  387. return {"target_path": str(target), "mirror_root": str(mirror_root), "inner_path": inner_path}
  388. def classify_sandbox_mirror_target(path: str) -> Optional[dict]:
  389. """Classify a write target as a sandbox-mirror of authoritative Hermes state: ``None``
  390. for non-mirror paths, else ``target_path`` (resolved), ``mirror_root`` (the
  391. ``…/home/.hermes`` prefix) and ``inner_path`` (what the agent meant on the host)."""
  392. target = _resolve_target(path)
  393. parts = target.parts if target is not None else ()
  394. # Need at least: sandboxes / <backend> / <task> / home / .hermes / <thing>; inner_idx = the .hermes part.
  395. inner_idx = next(
  396. (i + 4 for i, part in enumerate(parts)
  397. if part == "sandboxes" and i + 5 < len(parts) and parts[i + 3] == "home" and parts[i + 4] == ".hermes"),
  398. None,
  399. )
  400. if inner_idx is None:
  401. return None
  402. inner = str(Path(*parts[inner_idx + 1:])) if inner_idx + 1 < len(parts) else ""
  403. return _mirror_info(target, Path(*parts[: inner_idx + 1]), inner)
  404. def _mirror_warning(info: Optional[dict], body: str, bypass: str) -> Optional[str]:
  405. """Render ``_SANDBOX_MIRROR_WARNING`` for a classify_* result (``body`` may use ``{inner_path}``)."""
  406. if info is None:
  407. return None
  408. return _SANDBOX_MIRROR_WARNING.format(**info, body=body.format(inner_path=info["inner_path"]), bypass=bypass)
  409. def get_sandbox_mirror_warning(path: str) -> Optional[str]:
  410. """Model-facing soft-guard warning when ``path`` lands in a sandbox mirror, else ``None``;
  411. the caller surfaces it as a tool-result error and ``cross_profile=True`` bypasses."""
  412. return _mirror_warning(
  413. classify_sandbox_mirror_target(path),
  414. "a per-task mirror created by a non-local terminal backend (docker/daytona/etc.). "
  415. "Writes here land on a copy that the host Hermes process never reads — the "
  416. "authoritative file is likely {inner_path!r} under the real HERMES_HOME.",
  417. "this guard after explicit user direction, retry the call",
  418. )
  419. def classify_container_mirror_target(path: str, mirror_prefix: str | None = None) -> Optional[dict]:
  420. """Classify a write target as a container-side sandbox mirror. Inside the container
  421. the bind mount strips the ``sandboxes/`` prefix (the agent sees plain ``/root/.hermes/…``),
  422. so the caller supplies ``mirror_prefix`` once it knows file tools run in a docker sandbox.
  423. ``None`` without a prefix or outside it, else ``target_path``/``mirror_root``/``inner_path``."""
  424. target, mirror = _resolve_target(path), _resolve_target(mirror_prefix) if mirror_prefix else None
  425. if target is None or mirror is None or not _is_under(target, mirror):
  426. return None
  427. return _mirror_info(target, mirror, target.relative_to(mirror).as_posix())
  428. def get_container_mirror_warning(path: str, mirror_prefix: str | None = None) -> Optional[str]:
  429. """Model-facing soft-guard warning when ``path`` lands in the container's mirror, else ``None``."""
  430. return _mirror_warning(
  431. classify_container_mirror_target(path, mirror_prefix),
  432. "the container's bind-mounted home — a per-task mirror that the host Hermes "
  433. "process never reads. The authoritative file is {inner_path!r} under "
  434. "the real HERMES_HOME.",
  435. "after explicit user direction, retry",
  436. )