Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,13 @@ Changes are grouped by software version. Entries under Unreleased describe work

### Fixed

- `Sandbox.wrap` ran a virtual environment's interpreter (`<venv>/bin/python`, a link to its base interpreter) by
its real path, so it started without the environment and its packages failed to import. An interpreter whose
environment is granted (the sandbox's `readable` or `writable`, the call's, or `interpreters`) now runs by its own
name, with the links on its way to its installation shown; its `pyvenv.cfg` names no installation to show from a
call's grant, as before. An ungranted one runs as before, and so do one beneath a layout's root (`/w`), one
reached from its grant through a link to a place nothing shows, and one whose links lead to its installation
through a linked directory other than the system's (uv's version alias) (#95).
- A redeployment (`hermit deploy` into the same workspace) left a skill the new adapter no longer exports in the
host's skills folder (`.codex/skills`, `.claude/skills`, `.pi/skills`, `.opencode/skills`), where the agent still
loaded it, and a file a skill no longer has inside its copy. Each exported skill's copy is now replaced, and a
Expand Down
2 changes: 1 addition & 1 deletion docs/_includes/sandbox-build.html
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
<text class="t-m" x="146" y="174">its environment's site-packages, as installed</text>
<text class="t-m" x="644" y="166" text-anchor="end">read-only</text>
<text class="t-b" x="38" y="208">programs</text>
<text x="146" y="200">a command's own installation, run by its real path</text>
<text x="146" y="200">a command's own installation, run by its real path (a granted venv's python by its name)</text>
<text class="t-m" x="146" y="216">a CLI under ~/.local/bin and the package it belongs to</text>
<text class="t-m" x="644" y="208" text-anchor="end">read-only</text>
<rect class="b-band" x="26" y="224" width="628" height="42" rx="4"/>
Expand Down
6 changes: 5 additions & 1 deletion docs/guides/sandbox.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,11 @@ The pieces, in the order they are applied:
on hermit's environment (unless that directory's `python3` is another version, as on the host). The sandbox's own
command is found on the host's `PATH` before it starts: give a Python command as an absolute path
(`sys.executable`).
4. **Programs.** A command started by name is run by its real path. Its installation is shown (a CLI under
4. **Programs.** A command started by name is run by its real path, except a virtual environment's interpreter whose
environment is granted (for the sandbox or for the call), does not lie beneath a layout's root (the learner's
`/w`), is reached from its grant only through links to places shown too, and whose links lead to its
installation through no linked directory but the system's (`/bin`, `/lib`; not uv's version alias): it runs by its
own name, so it finds its `pyvenv.cfg` and the environment's packages. Its installation is shown (a CLI under
`~/.local/bin` and the package it belongs to, the interpreter its `#!` line names), with that installation's
Python packages emptied, unless the program itself runs on Python (a pipx or venv install keeps its own).
5. **Declared paths.** Task paths, the call's work directory, the learner's workspace (bound under `/w`), and the
Expand Down
6 changes: 3 additions & 3 deletions examples/aspire_robosuite/utils/agent/sim.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,9 +122,9 @@ def confine(cmd: list[str], *, root: Path, env: dict, writable=(), readable=(),
root = Path(root)
first = Path(cmd[0])
if (first.parent.parent / "pyvenv.cfg").is_file():
# A venv's interpreter (the validator's `python -c`): the sandbox runs a command by its real path, and the
# venv's python is a link to its base installation, which would run without the venv's packages; run by its
# own name through a shell, the venv (granted, so its base installation is shown too) is kept.
# A venv's interpreter (the validator's `python -c`), granted so its base installation is shown too. The
# sandbox runs a granted venv's interpreter by its own name (#95); the shell, which runs it by that name
# too, dates from before and is kept.
trusted = [first.parent.parent]
cmd = ["/bin/sh", "-c", 'exec "$0" "$@"', *cmd]
else:
Expand Down
94 changes: 91 additions & 3 deletions hermit/sandbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -437,6 +437,75 @@ def _names(path) -> list[str]:
return [given] if real == given else [given, real]


def _venv_root(found: str) -> str | None:
"""The virtual environment `found` is the interpreter of (a pyvenv.cfg beside it or one directory up), by the
name it is run by; else None."""
where = os.path.dirname(os.path.abspath(found))
return next((d for d in (where, os.path.dirname(where)) if os.path.isfile(os.path.join(d, "pyvenv.cfg"))), None)


def _granted_venv(found: str, granted) -> bool:
"""Whether `found` is a virtual environment's interpreter whose environment exists inside under the name it is
run by, as is the folder of `found` (_reachable from the places `granted` shows), and whose links lead to its
installation through no linked directory outside it but the system's (a venv made through uv's version alias
names the alias as its `home`, which nothing shows).
Its pyvenv.cfg is not read: the installation is shown, as for any program, by following the interpreter's links
(program_paths, and its links made again as links: _link_hops), never by a `home` a granted place could name."""
venv = _venv_root(found)
if venv is None:
return False
places = {n.rstrip("/") or "/" for g in granted for n in _names(g)} # a grant shown under both its names
if not any(_beneath(venv, w) for w in places):
return False # granted: shown is not enough (an ungranted one beneath /usr)
places |= set(ALWAYS_SHOWN) # shown whole as it is outside: a grant beneath it is that tree's, not bound
real = os.path.realpath(venv)
return _reachable(venv, places) and _reachable(os.path.dirname(os.path.abspath(found)), places) and not any(
os.path.realpath(h.parent) != str(h.parent) for h in _link_hops(found)
if not _beneath(str(h), venv) and not _beneath(os.path.realpath(h), real)
and not str(h).startswith(SYSTEM_LINKED))


# Shown inside as they are outside: /usr whole, and /lib, /lib64, /bin, /sbin as the same links (or directories).
SYSTEM_LINKED = ("/usr/", "/lib/", "/lib64/", "/bin/", "/sbin/")
ALWAYS_SHOWN = ("/usr",)


def _beneath(path: str, root: str) -> bool:
return path == root or path.startswith(root.rstrip("/") + "/")


def _reachable(path: str, places) -> bool:
"""Whether `path` exists inside: beneath a place shown at its own name, following the links below that place
(whose targets must be beneath a shown place too). A link above the place does not matter: the place is shown at
the name it was given. The outermost place is the one followed: a grant inside a bound one is that one's tree
inside (a linked grant there is not bound on its own)."""
current = os.path.abspath(path)
for _ in range(40):
place = min((w for w in places if _beneath(current, w)), key=len, default=None)
if place is None:
return False
rest, here = Path(current).relative_to(place).parts, Path(place)
for i, part in enumerate(rest):
here = here / part
if here.is_symlink():
current = os.path.normpath(os.path.join(here.parent, os.readlink(here), *rest[i + 1:]))
break
else:
return True
return False


def _link_hops(path: str) -> list[Path]:
"""The names on the way from `path`'s link to the file it leads to (a venv's bin/python -> an alias -> the
interpreter), each but `path` and the file itself, that lie outside `path`'s environment (shown with it): each
must exist inside for the first to start."""
venv = _venv_root(path)
hops = [Path(os.path.abspath(path))]
while hops[-1].is_symlink() and len(hops) < 20:
hops.append(Path(os.path.normpath(hops[-1].parent / os.readlink(hops[-1]))))
return [h for h in hops[1:] if str(h) != os.path.realpath(h) and not (venv and _beneath(str(h), venv))]


def _venv_paths() -> list[Path]:
"""The virtual environment's interpreter links and pyvenv.cfg. They are bound at their own path, unresolved: a
Python started as the link finds pyvenv.cfg beside it and so its environment; started as the file the link leads
Expand Down Expand Up @@ -1128,7 +1197,18 @@ def ours(first: str) -> bool: # a venv's python3 is its own bin/'s, not the
for first in (shutil.which(name, path=env["PATH"]) for name in ("python3", "python"))):
env["PATH"] = os.pathsep.join([own, *(p for p in env["PATH"].split(os.pathsep) if p and p != own)])
found = shutil.which(command[0]) if command else None
if found: # run the program by its real path: PATH entries outside the sandbox do not exist inside
# Not beneath a layout's root, where grants are shown under other names (a call's) or at their own (the
# sandbox's), and a link there may lead to where nothing is shown: such a venv runs as before.
moved = [p for p in [*readable, *writable] if self.layout and self._in_layout(p)
and self.translate(str(p), binds) != str(p)] # a call's grant shown under /w, not its name
by_name = bool(found) and not (self.layout and self._in_layout(os.path.dirname(os.path.abspath(found)))) \
and _granted_venv(found, [*self.readable, *self.writable, *interpreters,
*(p for p in [*readable, *writable] if p not in moved)])
if by_name:
# a granted virtual environment's interpreter, run by its own name: its real file is the base
# installation's, which, run as itself, finds no pyvenv.cfg and so not the environment's packages
command = [os.path.abspath(found), *command[1:]]
elif found: # run the program by its real path: PATH entries outside the sandbox do not exist inside
real = Path(found).resolve() # ... except this Python, which must keep its environment's path
command = [sys.executable if real == Path(sys.executable).resolve() else str(real), *command[1:]]
# A path given for this call at its own location but lying under the layout's root is shown where the
Expand Down Expand Up @@ -1167,7 +1247,7 @@ def bind(paths, flag, out, system=False):
if flag == "--bind" and not os.path.lexists(path): # a writable file stays a file
Path(path).mkdir(parents=True, exist_ok=True)
for name in _names(path):
if not os.path.exists(name) or (name.startswith("/usr") and not system):
if not os.path.exists(name) or (_beneath(name, "/usr") and not system): # not /usr2
continue
# A link under a directory bound already (uv's version alias of an interpreter kept inside a
# granted checkout) is there through that directory; binding it again fails on a link.
Expand Down Expand Up @@ -1196,7 +1276,15 @@ def bind(paths, flag, out, system=False):
and not any(os.path.realpath(p).startswith(m.rstrip("/") + "/") for m in mine)]
sites = list(dict.fromkeys(sites))
visible = self.visible(command, writable)
bind([p for p in [*visible, *interpreters, *trusted] if not any(_under(p, s) for s in sites)], "--ro-bind", ro)
hops = [h for h in (_link_hops(command[0]) if by_name else []) if not str(h).startswith(SYSTEM_LINKED)]
bind([p for p in [*visible, *interpreters, *trusted] if not any(_under(p, s) for s in sites)
and str(p) not in {str(h) for h in hops}], "--ro-bind", ro)
# A granted venv's interpreter reached through links elsewhere: each made again as the link it is, not bound
# (a copy of the interpreter there would take that folder for its $ORIGIN: a Python that loads ../lib's
# libpython would not find it), unless it is there through a directory bound already.
for hop in hops:
if hop.is_symlink() and not any(_beneath(str(hop), b) for b in (*ro, *rw)):
args.extend(["--symlink", os.readlink(hop), str(hop)])
# The interpreter's site directories hold every installed package: each is replaced by an empty directory,
# and the distributions this sandbox shows are bound back into it.
# A site directory is shown when it lies in a bound path or under /usr (bound whole above: a system Python).
Expand Down
Loading
Loading