Skip to content
Python

Inside an OpenShell sandbox: say what a blocked request means, and let the proxy look names up

Rohit C Prasadc47f4a53bc1a
diff --git a/coworker/agent.py b/coworker/agent.py
index a68a8b10..5da0637c 100644
--- a/coworker/agent.py
+++ b/coworker/agent.py
@@ -48,6 +48,7 @@ from .tools.toolreq import request_tool_tool
from .tools.subagent import explorer_tools
from .web import make_web_fetch_tool, make_web_search_tool
from .workspace_trust import WorkspaceTrustStore
+from .sandbox import inside as _openshell
from .sandbox.selection import select as select_sandbox
from .sandbox.workspace import open_workspace
from .tools.todo import TodoList
@@ -205,6 +206,10 @@ def _skill_dirs(workspace: Optional[Path]) -> list[Path]:
dirs = [state_dir() / "skills"]
if workspace is not None:
dirs.append(workspace / ".coworker" / "skills")
+ # Inside an OpenShell sandbox its own skills join the menu (sandbox/inside.py). The
+ # folder may be missing, or filled in later, when the user turns proposals on.
+ if _openshell.inside_openshell():
+ dirs.append(_openshell.SKILLS_DIR)
return dirs
@@ -310,6 +315,13 @@ def build_engine(
# it (2026-09-14: the first trial spilled under the run's log folder and read_file
# answered "path escapes the session's directories"). The workspace itself is never
# written to, so a repository or task tree stays clean.
+ # Inside an OpenShell sandbox the agent may read OpenShell's skills folder: the policy
+ # skill there points to a longer file beside it.
+ if _openshell.inside_openshell() and root_list and not any(
+ _is_within(_openshell.SKILLS_DIR, r.path) for r in root_list
+ ):
+ root_list.append(RootDir(path=_openshell.SKILLS_DIR, writable=False, label="openshell-skills"))
+
if tool_result_spill_dir is not None:
spill_dir: Optional[Path] = Path(tool_result_spill_dir).expanduser().resolve()
else:
@@ -657,6 +669,11 @@ def build_engine(
text = sandbox_ctx()
if text:
parts.append(text)
+ # OpenWorker itself inside an OpenShell sandbox: what a blocked request looks like
+ # and what to do. Read each turn, since the policy skill can appear mid-session.
+ openshell_ctx = _openshell.context()
+ if openshell_ctx:
+ parts.append(openshell_ctx)
# Live skill menu (SKILLS-SPEC §4.1): recomputed every turn like the roots list, so
# a skill installed/enabled/disabled mid-session applies from the NEXT MESSAGE —
# no new session, no lost context.
diff --git a/coworker/sandbox/inside.py b/coworker/sandbox/inside.py
new file mode 100644
index 00000000..0600e9da
--- /dev/null
+++ b/coworker/sandbox/inside.py
@@ -0,0 +1,71 @@
+"""OpenWorker running INSIDE an OpenShell sandbox (`openshell sandbox create -- openworker run …`).
+
+Not a mode: OpenShell is the wall, and OpenWorker's own sandbox is off, as it is on any
+computer that has not turned one on. OpenShell says it is there with `OPENSHELL_SANDBOX=1`,
+and three things follow from that, all here:
+
+- the agent is told what a blocked request looks like and what to do about it;
+- OpenShell's own skills folder is readable, so the agent can follow OpenShell's policy
+ skill as OpenShell prescribes (it exists only when the user turned proposals on);
+- the web tools leave the name lookup to OpenShell's proxy (web/guard.py): inside the
+ sandbox no name resolves and nothing connects directly.
+
+Sites are added from outside the sandbox with OpenShell's own commands. OpenWorker does not
+grant them, so `request_network_access` and the allowed-sites card are not part of this.
+"""
+
+from __future__ import annotations
+
+import os
+from pathlib import Path
+
+# Where OpenShell writes its agent-facing skills. The policy skill appears when the
+# sandbox's `agent_policy_proposals_enabled` setting is on, and can appear mid-session.
+SKILLS_DIR = Path("/etc/openshell/skills")
+POLICY_SKILL = "openshell-policy-advisor"
+_POLICY_SKILL_FILE = Path("policy-advisor") / "SKILL.md"
+
+
+def inside_openshell() -> bool:
+ return os.environ.get("OPENSHELL_SANDBOX", "").strip() == "1"
+
+
+def policy_skill_present() -> bool:
+ try:
+ return (SKILLS_DIR / _POLICY_SKILL_FILE).is_file()
+ except OSError:
+ return False
+
+
+def proxied(scheme: str) -> bool:
+ """Whether a request of this scheme leaves through a proxy named in the environment
+ (the way OpenShell routes everything). The HTTP client reads the same variables."""
+ names = ("HTTPS_PROXY", "https_proxy") if scheme == "https" else ("HTTP_PROXY", "http_proxy")
+ return any(os.environ.get(name, "").strip() for name in (*names, "ALL_PROXY", "all_proxy"))
+
+
+def context() -> str:
+ """The lines the agent reads each turn. Empty outside OpenShell."""
+ if not inside_openshell():
+ return ""
+ lines = [
+ "This session runs inside an OpenShell sandbox. Every network request, from your "
+ "commands and your web tools alike, goes through its proxy, which allows only what "
+ "its policy lists. A request the policy does not allow fails with a 403 from the "
+ "proxy (for example `CONNECT tunnel failed, response 403`) or says `policy_denied`. "
+ "That means the sandbox blocked it. Do not retry it unchanged, and do not look for "
+ "another route to the same place."
+ ]
+ if policy_skill_present():
+ lines.append(
+ f"If the task needs a blocked request, load the skill `{POLICY_SKILL}` and follow "
+ "it: it explains how to ask for the access, which a person outside the sandbox "
+ "approves."
+ )
+ else:
+ lines.append(
+ "If the task needs a blocked request, tell the user which host and port were "
+ "blocked. They can allow it from outside the sandbox with "
+ "`openshell policy update --add-endpoint HOST:PORT`."
+ )
+ return " ".join(lines)
diff --git a/coworker/web/guard.py b/coworker/web/guard.py
index 5ceab0cb..84b93140 100644
--- a/coworker/web/guard.py
+++ b/coworker/web/guard.py
@@ -77,6 +77,15 @@ def _vet(url: str) -> tuple[Optional[str], Optional[str]]:
reason = _blocked_reason(literal)
return (f"refusing to fetch {host}: {reason}" if reason else None), None
+ # Inside an OpenShell sandbox no name resolves and nothing connects directly: every
+ # request goes to OpenShell's proxy, which looks the name up itself and holds it to the
+ # sandbox's policy. So the name is not vetted or pinned here; the client hands it to
+ # the proxy. (A literal address was still judged above.)
+ from ..sandbox.inside import inside_openshell, proxied
+
+ if inside_openshell() and proxied(parts.scheme):
+ return None, None
+
try:
infos = socket.getaddrinfo(host, parts.port or (443 if parts.scheme == "https" else 80),
proto=socket.IPPROTO_TCP)
diff --git a/tests/test_openshell_inside.py b/tests/test_openshell_inside.py
new file mode 100644
index 00000000..396a2738
--- /dev/null
+++ b/tests/test_openshell_inside.py
@@ -0,0 +1,160 @@
+"""OpenWorker running inside an OpenShell sandbox (`OPENSHELL_SANDBOX=1`): the agent is
+told what a blocked request looks like, OpenShell's own skills are readable, and the web
+tools leave the name lookup to OpenShell's proxy. Outside OpenShell nothing changes."""
+
+from __future__ import annotations
+
+import socket
+from pathlib import Path
+
+import pytest
+
+from coworker.agent import build_engine
+from coworker.agents.cowork import cowork_agent
+from coworker.sandbox import inside
+from coworker.web import guard
+
+PROXY_ENV = ("HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy")
+
+
+class _StubProvider:
+ def complete(self, **_kw): # pragma: no cover - never called at build time
+ from coworker.providers import AssistantTurn
+
+ return AssistantTurn()
+
+ def capabilities(self, _model): # pragma: no cover
+ from coworker.providers.base import ModelCapabilities
+
+ return ModelCapabilities()
+
+
+def outside(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.delenv("OPENSHELL_SANDBOX", raising=False)
+ for name in PROXY_ENV:
+ monkeypatch.delenv(name, raising=False)
+
+
+def in_openshell(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> Path:
+ """Inside a sandbox whose proposals are off: no skills folder yet."""
+ for name in PROXY_ENV:
+ monkeypatch.delenv(name, raising=False)
+ monkeypatch.setenv("OPENSHELL_SANDBOX", "1")
+ monkeypatch.setenv("HTTPS_PROXY", "http://10.200.0.1:3128")
+ skills = tmp_path / "etc-openshell-skills"
+ monkeypatch.setattr(inside, "SKILLS_DIR", skills)
+ return skills
+
+
+def _turn_on_proposals(skills: Path) -> None:
+ """What OpenShell writes when `agent_policy_proposals_enabled` is set."""
+ (skills / "policy-advisor").mkdir(parents=True)
+ (skills / "policy-advisor" / "SKILL.md").write_text(
+ "---\nname: openshell-policy-advisor\n"
+ "description: Use when an OpenShell sandbox returns policy_denied.\n---\n\n"
+ "Read `/etc/openshell/skills/policy_advisor.md`.\n",
+ encoding="utf-8",
+ )
+ (skills / "policy_advisor.md").write_text("# OpenShell Policy Advisor\n", encoding="utf-8")
+
+
+def _engine(tmp_path: Path):
+ ws = tmp_path / "ws"
+ ws.mkdir()
+ return build_engine(agent=cowork_agent(), workspace=ws, provider=_StubProvider())
+
+
+# -- what the agent is told -------------------------------------------------------------
+
+
+def test_outside_openshell_nothing_is_said_or_added(outside, tmp_path: Path) -> None:
+ assert inside.context() == ""
+ engine = _engine(tmp_path)
+ assert "OpenShell" not in engine.context_provider()
+ assert [r.label for r in engine.roots if r.label == "openshell-skills"] == []
+
+
+def test_inside_the_agent_is_told_what_a_blocked_request_looks_like(in_openshell: Path, tmp_path: Path) -> None:
+ text = _engine(tmp_path).context_provider()
+ assert "runs inside an OpenShell sandbox" in text
+ assert "CONNECT tunnel failed, response 403" in text and "policy_denied" in text
+ # Proposals are off, so there is no skill to load: the person changes the policy.
+ assert "openshell policy update --add-endpoint HOST:PORT" in text
+ assert "openshell-policy-advisor" not in text
+
+
+def test_with_proposals_on_the_agent_is_pointed_at_openshells_skill(in_openshell: Path, tmp_path: Path) -> None:
+ _turn_on_proposals(in_openshell)
+ engine = _engine(tmp_path)
+ text = engine.context_provider()
+ assert "load the skill `openshell-policy-advisor`" in text
+ assert "openshell policy update" not in text
+ # The skill is on the menu under OpenShell's own name and description…
+ assert "Use when an OpenShell sandbox returns policy_denied." in text
+ assert engine.skill_loader.get("openshell-policy-advisor") is not None
+ # …and its folder is one the agent may read, never write.
+ (root,) = [r for r in engine.roots if r.label == "openshell-skills"]
+ assert root.path == in_openshell.resolve() and root.writable is False
+
+
+def test_proposals_turned_on_mid_session_are_picked_up_on_the_next_turn(in_openshell: Path, tmp_path: Path) -> None:
+ engine = _engine(tmp_path)
+ assert "openshell policy update" in engine.context_provider()
+ _turn_on_proposals(in_openshell)
+ text = engine.context_provider()
+ assert "load the skill `openshell-policy-advisor`" in text
+ assert "Use when an OpenShell sandbox returns policy_denied." in text
+
+
+# -- web tools --------------------------------------------------------------------------
+
+
+def _no_lookup(*_a, **_k):
+ raise AssertionError("the name must not be looked up here")
+
+
+def test_inside_a_name_goes_to_the_proxy_without_a_lookup(in_openshell, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(socket, "getaddrinfo", _no_lookup)
+ assert guard._vet("https://example.org/page") == (None, None)
+
+ class Client:
+ def __init__(self) -> None:
+ self.asked: list[str] = []
+
+ def get(self, url, **kwargs):
+ self.asked.append(url)
+ assert not kwargs # no pinned address, no Host override: the name as written
+ return type("R", (), {"status_code": 200, "extensions": {}})()
+
+ client = Client()
+ resp = guard.get_checked(client, "https://example.org/page")
+ assert client.asked == ["https://example.org/page"]
+ assert resp.extensions["logical_url"] == "https://example.org/page"
+
+
+def test_inside_a_literal_internal_address_is_still_refused(in_openshell, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(socket, "getaddrinfo", _no_lookup)
+ for url in ("http://169.254.169.254/latest/meta-data/", "https://127.0.0.1:8443/", "https://10.0.0.5/"):
+ reason, pin = guard._vet(url)
+ assert reason and "refusing to fetch" in reason and pin is None
+
+
+def test_inside_without_a_proxy_for_the_scheme_the_name_is_still_vetted(in_openshell, monkeypatch: pytest.MonkeyPatch) -> None:
+ # Only HTTPS_PROXY is set: a plain http request would connect directly, so it is checked.
+ looked_up: list[str] = []
+
+ def lookup(host, *_a, **_k):
+ looked_up.append(host)
+ return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("127.0.0.1", 80))]
+
+ monkeypatch.setattr(socket, "getaddrinfo", lookup)
+ reason, _pin = guard._vet("http://rebind.example.org/")
+ assert looked_up == ["rebind.example.org"] and reason and "refusing to fetch" in reason
+
+
+def test_outside_a_name_is_looked_up_and_pinned_as_before(outside, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("HTTPS_PROXY", "http://proxy.example:3128") # a proxy alone changes nothing
+ monkeypatch.setattr(socket, "getaddrinfo", lambda *_a, **_k: [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("93.184.216.34", 443))])
+ assert guard._vet("https://example.org/") == (None, "93.184.216.34")