run_inbound_media.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. """Inbound attachment re-homing for multiplexed gateways (moved out of ``gateway/run_inbound.py``)."""
  2. from __future__ import annotations
  3. import logging
  4. import shutil
  5. from pathlib import Path
  6. from gateway.platforms.event import MessageEvent
  7. # Log-record parity with the origin module.
  8. logger = logging.getLogger("gateway.run")
  9. def rehome_inbound_media(event: MessageEvent) -> None:
  10. """Move adapter-cached attachments into the ACTIVE profile's ``cache/`` and repoint the event.
  11. Adapters download and cache an attachment BEFORE the gateway routes the event to a profile, so
  12. on a multiplexed gateway the file lands under the launch home while the routed turn's sandbox
  13. mounts (``get_cache_directory_mounts``) and vision's ``_media_cache_roots`` resolve the routed
  14. profile's ``cache/`` — the agent is handed a mounted, empty directory (#101134). Runs inside the
  15. routed scope at the shared preprocessing choke point (every adapter, every media kind); a no-op
  16. when the active home is the launch home, and idempotent (a moved entry is no longer under it).
  17. """
  18. if not event.media_urls:
  19. return
  20. from hermes_constants import get_hermes_home, get_routing_process_hermes_home, hermes_home_key
  21. active, launch = Path(get_hermes_home()), Path(get_routing_process_hermes_home())
  22. if hermes_home_key(active) == hermes_home_key(launch):
  23. return
  24. from tools.credential_files import to_agent_visible_cache_path
  25. rewritten = list(event.media_urls)
  26. for i, raw in enumerate(event.media_urls):
  27. src = Path(raw)
  28. try:
  29. rel = src.relative_to(launch / "cache")
  30. except ValueError:
  31. continue
  32. dest = active / "cache" / rel
  33. try:
  34. if not src.is_file():
  35. continue
  36. dest.parent.mkdir(parents=True, exist_ok=True)
  37. shutil.move(str(src), str(dest))
  38. except OSError:
  39. logger.warning("Could not move inbound attachment %s into the routed profile's cache", raw, exc_info=True)
  40. continue
  41. rewritten[i] = str(dest)
  42. if event.text and raw in event.text: # note an adapter already baked in (observed/replied media)
  43. event.text = event.text.replace(raw, to_agent_visible_cache_path(str(dest)))
  44. event.media_urls = rewritten