docker_media_paths.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. """Host directories that stand in for a Docker container's ``/workspace`` and ``/root``.
  2. ``base.py`` is over the file-size ratchet, so the candidate list lives here.
  3. The workspace digest is passed in: delivery runs after the turn's context is
  4. gone, and scanning every ``*_ws_*`` directory would serve another session's file.
  5. """
  6. from __future__ import annotations
  7. import os
  8. import re
  9. from pathlib import Path
  10. _WORKSPACE_KEY_RE = re.compile(r"^[0-9a-f]{16}$")
  11. def _scope():
  12. from gateway.platforms.base import _docker_persistent_active, _tenv
  13. return _tenv, _docker_persistent_active
  14. def _cwd_mount_enabled() -> bool:
  15. """The terminal's own predicate, so the file panel agrees with what the container mounted."""
  16. from tools.terminal_tool_config import _tenv_bool
  17. return _tenv_bool("TERMINAL_DOCKER_MOUNT_CWD_TO_WORKSPACE", "false")
  18. def _docker_sandbox_dir_candidates(session_key: str = "", workspace_key: str = "") -> list[str]:
  19. """Candidate host sandbox dir names, best first.
  20. Mirrors ``_resolve_container_task_id``: profile scope (``default``, else
  21. ``profile:<name>``), then the legacy ``session:<key>`` layout. A session
  22. that bound a host workspace also has ``<base>:ws:<digest>`` — a different
  23. directory from the shared profile sandbox — but only with the cwd mount on:
  24. without it every session keeps the profile sandbox, and a ``*_ws_*`` dir
  25. left by an older build is not this session's. The digest is explicit because
  26. an ambient lookup after the turn would collapse onto ``default``.
  27. """
  28. tenv, _persistent = _scope()
  29. try:
  30. from tools.environments.path_utils import sanitize_task_id_for_path
  31. from tools.terminal_tool_config import home_profile_name, profile_container_key
  32. base = profile_container_key(home_profile_name())
  33. except Exception: # health: allow BLE001 -- path translation fails closed; a miss is a 404, not a 500
  34. return ["default"]
  35. candidates: list[str] = []
  36. # Explicit trusted-profiles opt-in: one shared container identity. That
  37. # key is not a per-workspace container, so a :ws: digest does not apply.
  38. if shared := tenv("TERMINAL_DOCKER_SHARED_CONTAINER_KEY", "").strip():
  39. candidates.append(sanitize_task_id_for_path(f"shared:{shared}"))
  40. elif _WORKSPACE_KEY_RE.fullmatch(workspace_key or "") and _cwd_mount_enabled():
  41. candidates.append(sanitize_task_id_for_path(f"{base}:ws:{workspace_key}"))
  42. if base != "default":
  43. candidates.append(sanitize_task_id_for_path(base))
  44. candidates.append("default")
  45. if session_key: # bug-window legacy layout: per-session sandboxes
  46. candidates.append(sanitize_task_id_for_path(f"session:{session_key}"))
  47. return candidates
  48. def _docker_persistent_sandbox_roots(
  49. session_key: str, leaf: str, workspace_key: str = "",
  50. ) -> list[Path]:
  51. """Existing ``<sandbox>/docker/<candidate>/<leaf>`` dirs, candidate order.
  52. Empty unless Docker + persistent. The translator tries each until the file
  53. resolves.
  54. """
  55. _tenv, persistent = _scope()
  56. if not persistent():
  57. return []
  58. try:
  59. from tools.environments.base import get_sandbox_dir
  60. base = get_sandbox_dir() / "docker"
  61. return [cand for name in _docker_sandbox_dir_candidates(session_key, workspace_key)
  62. if (cand := (base / name / leaf).resolve(strict=False)).is_dir()]
  63. except Exception: # health: allow BLE001 -- path translation fails closed; a miss is a 404, not a 500
  64. return []
  65. def _mounted_workspace_cwd(workspace_cwd: str = "") -> list[Path]:
  66. tenv, _persistent = _scope()
  67. cwd = workspace_cwd or tenv("TERMINAL_CWD") or os.getcwd()
  68. try:
  69. host = Path(os.path.expanduser(cwd)).resolve(strict=False)
  70. except (OSError, RuntimeError, ValueError):
  71. return []
  72. return [host] if host.is_dir() else []
  73. def _session_mounted_workspace(workspace_key: str, workspace_cwd: str) -> list[Path]:
  74. """The host dir a session bound to a workspace mounts at ``/workspace``, or nothing.
  75. A gateway turn runs with the session's own cwd as ``TERMINAL_CWD``
  76. (``gateway.session_policy.build_policy``), and that cwd is also what
  77. ``bind_turn_workspace`` registers and hashes into ``workspace_key``. So the
  78. mount is that cwd, never the profile's ``terminal.cwd``. A cwd whose digest
  79. is not ``workspace_key`` names some other container's mount: no root.
  80. """
  81. from tools.terminal_tool import workspace_key_for
  82. cwd = (workspace_cwd or "").strip()
  83. if not cwd or "\0" in cwd or not os.path.isabs(os.path.expanduser(cwd)):
  84. return []
  85. if workspace_key_for(cwd) != workspace_key:
  86. return []
  87. return _mounted_workspace_cwd(cwd)
  88. def _shared_cwd_mount_guess(workspace_key: str) -> list[Path]:
  89. """The profile cwd that stands in for a shared container's ``/workspace``, or nothing.
  90. With ``TERMINAL_DOCKER_SHARED_CONTAINER_KEY`` every session reuses one
  91. ``shared:<key>`` container, which mounts whatever cwd the session that
  92. created it brought, so a session's own cwd is not its mount. Nothing records
  93. that first cwd: shared containers carry no mount fingerprint label, and a
  94. cross-process attach never inspects the container's mounts. Reads keep the
  95. profile cwd, as before; a session Save there is a guess the caller refuses.
  96. """
  97. tenv, persistent = _scope()
  98. if not persistent() or not _WORKSPACE_KEY_RE.fullmatch(workspace_key or ""):
  99. return []
  100. if not _cwd_mount_enabled():
  101. return []
  102. if not tenv("TERMINAL_DOCKER_SHARED_CONTAINER_KEY", "").strip():
  103. return []
  104. return _mounted_workspace_cwd()
  105. def _default_docker_workspace_host_roots(
  106. session_key: str = "", workspace_key: str = "", workspace_cwd: str = "",
  107. ) -> list[Path]:
  108. """Host dirs that stand in for ``/workspace``.
  109. A cwd mount is tried first. With no workspace digest that mount is the
  110. profile's cwd and the only candidate, so MEDIA delivery (which has no
  111. session) stays cwd-only. A download that names a digest mounts that
  112. session's own cwd (``workspace_cwd``) instead, unless its container is a
  113. shared one (``_shared_cwd_mount_guess``), then tries that session's
  114. sandbox: the container key can be ``default:ws:<digest>`` while
  115. ``/workspace`` is still the sandbox directory, because the host cwd was
  116. not bind-mounted when the container was created.
  117. """
  118. tenv, persistent = _scope()
  119. if not persistent():
  120. return []
  121. roots: list[Path] = []
  122. if _cwd_mount_enabled():
  123. if not _WORKSPACE_KEY_RE.fullmatch(workspace_key or ""):
  124. return _mounted_workspace_cwd()
  125. if tenv("TERMINAL_DOCKER_SHARED_CONTAINER_KEY", "").strip():
  126. roots.extend(_shared_cwd_mount_guess(workspace_key))
  127. else:
  128. roots.extend(_session_mounted_workspace(workspace_key, workspace_cwd))
  129. for root in _docker_persistent_sandbox_roots(session_key, "workspace", workspace_key):
  130. if root not in roots:
  131. roots.append(root)
  132. return roots