Skip to content
Python

The agent can ask for a site its commands cannot reach

Rohit C Prasad84215788abaa
diff --git a/coworker/agent.py b/coworker/agent.py
index 27592ae3..9325bee5 100644
--- a/coworker/agent.py
+++ b/coworker/agent.py
@@ -742,7 +742,8 @@ def build_engine(
def _open_site(host: str) -> None:
# The running sandbox takes the site too, so commands reach it from now on. A
- # failure here must not undo the person's choice for the web tools: log it.
+ # failure is logged and raised: the permission engine keeps it, so the agent
+ # and the app can say that commands still lack the site.
import logging
from .sandbox.network_profiles import clean_host
@@ -751,9 +752,16 @@ def build_engine(
sandbox_workspace.add_hosts([clean_host(host)])
except Exception as exc: # noqa: BLE001
logging.getLogger(__name__).warning("could not open %s on the session's sandbox: %s", host, exc)
+ raise
engine.permissions.grant_site = _grant_site
engine.permissions.open_site = _open_site
+ # The agent can ask for a site, except where nobody can answer (full access).
+ from .permissions import Mode as _Mode
+ from .tools.network import request_network_access_tool
+
+ registry.register(request_network_access_tool(engine.permissions))
+ sandbox_workspace.can_ask_network = lambda: engine.permissions.mode is not _Mode.BYPASS_APPROVALS
engine.todo = todo # type: ignore[attr-defined]
engine.agent_name = agent.name # type: ignore[attr-defined]
engine.roots = root_list # type: ignore[attr-defined] # shared list; Slice C mutates in place
diff --git a/coworker/engine.py b/coworker/engine.py
index 72afe142..0e6e51c4 100644
--- a/coworker/engine.py
+++ b/coworker/engine.py
@@ -1704,6 +1704,14 @@ class TurnEngine:
# OPE-219: the host the sandbox's allowed-sites wall stopped. The card
# says so and offers to add the site to the machine's list.
**({"site_wall": decision.site} if decision.site else {}),
+ # The agent asked for sites its commands cannot reach: the card names
+ # them, gives the agent's reason, and says whether the sandbox has in
+ # fact blocked each one (the person's check on the request).
+ **(
+ {"network_request": self._network_request_payload(tool_call, decision)}
+ if decision.network_hosts
+ else {}
+ ),
# The exact target a standing rule could pin, or None when the call
# isn't eligible (no declared target arg / exec risk). Surfaces use it
# to offer "Allow every time" on automation-run approval cards only.
@@ -1800,7 +1808,15 @@ class TurnEngine:
reason=reason,
)
else:
- if outcome is ApprovalOutcome.ALWAYS_TOOL:
+ if decision.network_hosts:
+ # Any approval of a network request opens the sites for this session;
+ # "Always allow" also stores them. Never a tool-wide grant: each ask
+ # for a new site gets its own card.
+ self.permissions.allow_network_hosts(
+ decision.network_hosts,
+ always=outcome is ApprovalOutcome.ALWAYS_SITE,
+ )
+ elif outcome is ApprovalOutcome.ALWAYS_TOOL:
self.permissions.allow_tool_for_session(tool_call.name)
elif outcome is ApprovalOutcome.ALWAYS_COMMAND:
self.permissions.allow_command_for_session(
@@ -2369,6 +2385,28 @@ class TurnEngine:
},
)
+ def _network_request_payload(self, tool_call: ToolCall, decision: Any) -> dict[str, Any]:
+ """What the network-access card shows: each site, and how long ago the session's
+ sandbox last blocked it (None when no command has tried it). `evidence` is false
+ where the sandbox cannot say what it blocked; the card then claims nothing."""
+ last: dict[str, float] = {}
+ workspace = getattr(self, "sandbox_workspace", None)
+ evidence = bool(getattr(workspace, "reports_blocked", False))
+ try:
+ for when, entry in (workspace.blocked_since(0.0) if evidence else []):
+ last[entry] = max(when, last.get(entry, 0.0))
+ except Exception: # noqa: BLE001 - evidence is a help, never a reason to fail the card
+ last, evidence = {}, False
+ now = time.time()
+ return {
+ "reason": str((tool_call.arguments or {}).get("reason", ""))[:500],
+ "evidence": evidence,
+ "hosts": [
+ {"host": entry, "blocked_seconds_ago": (max(0, int(now - last[entry])) if entry in last else None)}
+ for entry in decision.network_hosts
+ ],
+ }
+
async def _handle_directory_request(
self, tool_call: ToolCall
) -> AsyncIterator[Event]:
diff --git a/coworker/permissions.py b/coworker/permissions.py
index dbaf7ed9..decc8977 100644
--- a/coworker/permissions.py
+++ b/coworker/permissions.py
@@ -13,7 +13,7 @@ import shlex
from dataclasses import dataclass, field
from enum import Enum
from pathlib import Path
-from typing import Any, Callable, Optional
+from typing import Any, Callable, Optional, Sequence
from urllib.parse import urlsplit
# Constructs whose *contents* we cannot evaluate, so a command carrying one is never
@@ -93,6 +93,37 @@ PERSISTENT_AUTHORITY_TOOLS = {
}
+# The agent's way to ask for a site its commands cannot reach (OPE-219). It changes what the
+# sandbox lets out, so only a person answers it, and full access cannot grant it.
+NETWORK_ACCESS_TOOL = "request_network_access"
+NETWORK_ACCESS_MAX_HOSTS = 5
+
+
+def network_request_hosts(arguments: dict[str, Any]) -> tuple[list[str], list[str]]:
+ """The hosts a `request_network_access` call names, as ("host:port" entries, rejected
+ inputs). Exact host names only: no wildcards, no addresses, nothing that is not a name,
+ since the entry is shown to a person and opened on the sandbox as written."""
+ from .sandbox.network_profiles import clean_host
+
+ raw = (arguments or {}).get("hosts")
+ items = [raw] if isinstance(raw, str) else list(raw or []) if isinstance(raw, (list, tuple)) else []
+ good: list[str] = []
+ bad: list[str] = []
+ for item in items:
+ text = str(item or "").strip()
+ try:
+ entry = clean_host(text)
+ except ValueError:
+ bad.append(text[:80])
+ continue
+ name = entry.rsplit(":", 1)[0]
+ if name.startswith("*.") or name.replace(".", "").isdigit():
+ bad.append(text[:80])
+ elif entry not in good:
+ good.append(entry)
+ return good, bad
+
+
def protected_paths() -> list[Path]:
"""Files that govern the permission system itself. Nothing the agent does may write
these — in any mode, through any tool. The escalation this blocks is: approve one
@@ -261,6 +292,8 @@ class Decision:
# The host the sandbox's allowed-sites wall stopped (OPE-219). The card then says why
# it is asking and offers to add the site to the list.
site: str = ""
+ # The "host:port" entries a `request_network_access` call still needs a person for.
+ network_hosts: tuple[str, ...] = ()
def standing_rule_candidate(
@@ -315,6 +348,11 @@ class PermissionEngine:
grant_site: Optional[Callable[[str], Optional[list[str]]]] = None
# Opens a site on the session's running sandbox, so commands reach it too (OPE-219).
open_site: Optional[Callable[[str], None]] = None
+ # "host:port" entries a person allowed for this session only (either card, or the
+ # session's own list in the app). The machine's list is `sandbox_sites`.
+ session_sites: list[str] = field(default_factory=list)
+ # A site the person allowed that the running sandbox could not take: entry -> why.
+ site_open_errors: dict[str, str] = field(default_factory=dict)
# Session-wide read-only grant (owner ask 2026-08-11): auto-allow shell commands the
# conservative classifier (coworker/readonly.py) accepts. User-elected per session.
session_readonly: bool = False
@@ -376,7 +414,9 @@ class PermissionEngine:
# this"; the OPE-136 gate-order pin caught that the class-based check alone
# didn't deliver it (save_skill in Discuss reached the human-only card).
consequential = (
- is_consequential(risk) or tool_name in PERSISTENT_AUTHORITY_TOOLS
+ is_consequential(risk)
+ or tool_name in PERSISTENT_AUTHORITY_TOOLS
+ or tool_name == NETWORK_ACCESS_TOOL
)
# SELF-PROTECTION FLOOR — runs before mode, allowlists and every auto-approve path,
@@ -421,6 +461,11 @@ class PermissionEngine:
if _is_protected_in_project(self._candidate(path)):
needs_human_for_protected = True
+ # Asking for a site (OPE-219): a change to the allowed-sites wall. Only a person
+ # answers it; full access cannot, like every other change to a wall.
+ if tool_name == NETWORK_ACCESS_TOOL:
+ return self._evaluate_network_request(arguments)
+
# Authority outliving the session reaches a person, over the reviewer and over
# every allowlist below (OPE-117). Placed ahead of the non-consequential return on
# purpose: these tools are consequential today, but a metadata slip must not be
@@ -628,8 +673,7 @@ class PermissionEngine:
self.sandbox_sites[:] = [str(x) for x in stored]
else:
self.session_allow_domains.add(host)
- if self.open_site is not None:
- self.open_site(host)
+ self._open(host)
def allow_site_for_session(self, url_or_domain: str) -> None:
""""Allow for this session" on the allowed-sites card: the web tools and, through the
@@ -638,8 +682,95 @@ class PermissionEngine:
if not host:
return
self.allow_domain_for_session(host)
- if self.open_site is not None:
- self.open_site(host)
+ self._note_session_site(host)
+ self._open(host)
+
+ def allow_network_hosts(self, entries: Sequence[str], *, always: bool) -> None:
+ """A person allowed these "host:port" entries (the network-access card, or the
+ session's list in the app): for this session, or for good when `always` and a store
+ is wired. Commands reach them through the running sandbox; the web tools too."""
+ for entry in entries:
+ host = str(entry).rsplit(":", 1)[0]
+ if always and self.grant_site is not None:
+ stored = self.grant_site(str(entry))
+ if stored is not None and self.sandbox_sites is not None:
+ self.sandbox_sites[:] = [str(x) for x in stored]
+ else:
+ self.session_allow_domains.add(host)
+ self._note_session_site(str(entry))
+ self._open(str(entry))
+
+ def _note_session_site(self, host_or_entry: str) -> None:
+ from .sandbox.network_profiles import clean_host
+
+ try:
+ entry = clean_host(host_or_entry)
+ except ValueError:
+ return
+ if entry not in self.session_sites and not self._entry_allowed(entry):
+ self.session_sites.append(entry)
+
+ def _open(self, host_or_entry: str) -> None:
+ """Tell the running sandbox. A failure does not undo the person's choice for the
+ web tools; it is kept so the agent and the app can say the commands lack the site."""
+ if self.open_site is None:
+ return
+ try:
+ self.open_site(host_or_entry)
+ self.site_open_errors.pop(host_or_entry, None)
+ except Exception as exc: # noqa: BLE001
+ self.site_open_errors[host_or_entry] = str(exc) or type(exc).__name__
+
+ def _entry_allowed(self, entry: str) -> bool:
+ """Whether a "host:port" entry is already open to this session's commands: on the
+ machine's list (same port; `*.example.com` covers subdomains) or allowed for the
+ session."""
+ from .sandbox.network_profiles import clean_host
+
+ if entry in self.session_sites:
+ return True
+ host, _, port = entry.rpartition(":")
+ for item in self.sandbox_sites or []:
+ try:
+ name, _, item_port = clean_host(str(item)).rpartition(":")
+ except ValueError:
+ continue
+ if item_port != port:
+ continue
+ if name.startswith("*."):
+ if host.endswith(name[1:]) and host != name[2:]:
+ return True
+ elif host == name:
+ return True
+ return False
+
+ def _evaluate_network_request(self, arguments: dict[str, Any]) -> Decision:
+ if self.sandbox_sites is None:
+ return Decision(False, "this session has no allowed-sites list to change", needs_user=False)
+ wanted, bad = network_request_hosts(arguments)
+ if bad or not wanted or len(wanted) > NETWORK_ACCESS_MAX_HOSTS:
+ return Decision(
+ False,
+ f"give `hosts` as one to {NETWORK_ACCESS_MAX_HOSTS} exact host names, such as registry.npmjs.org "
+ "or db.example.com:5432 (no wildcards, no IP addresses)" + (f"; not accepted: {', '.join(bad)}" if bad else ""),
+ needs_user=False,
+ )
+ pending = [entry for entry in wanted if not self._entry_allowed(entry)]
+ if not pending:
+ return Decision(True, "already on the allowed sites")
+ if self.mode is Mode.BYPASS_APPROVALS:
+ return Decision(
+ False,
+ "The allowed sites cannot be changed from this session. Tell the user; they can add the site in Settings > Sandbox > Choose sites.",
+ needs_user=False,
+ )
+ return Decision(
+ False,
+ "asks to let this session's commands reach " + ", ".join(e[:-4] if e.endswith(":443") else e for e in pending),
+ needs_user=True,
+ human_only=True,
+ network_hosts=tuple(pending),
+ )
def egress_host(self, tool_name: str, arguments: dict[str, Any]) -> str:
"""Where an egress tool is going: its url's host, or for `web_search` (a fixed
diff --git a/coworker/sandbox/executor.py b/coworker/sandbox/executor.py
index df7ae097..a74a5e83 100644
--- a/coworker/sandbox/executor.py
+++ b/coworker/sandbox/executor.py
@@ -9,6 +9,7 @@ same to the model in both modes.
from __future__ import annotations
import threading
+import time
from typing import Any, Callable, Optional
from .client import RunnerClient
@@ -30,11 +31,15 @@ class RunnerExecutor(Executor):
default_timeout: float = _DEFAULT_TIMEOUT,
on_output: Optional[Callable[[str], None]] = None,
before_call: Optional[Callable[[], Optional[str]]] = None,
+ after_call: Optional[Callable[[float], Optional[dict[str, Any]]]] = None,
) -> None:
self._client = client
# Called before every command. The workspace uses it to restart the sandbox when the
# session's folders changed; what it returns is told to the agent with the result.
self._before_call = before_call
+ # Called after every command with the time it started; the fields it returns join
+ # the result (the workspace reports what the sandbox's network rules blocked).
+ self._after_call = after_call
self.shell = shell
self.cwd = str(cwd) # the last folder the runner reported; a reopened shell starts here
self.default_timeout = default_timeout
@@ -54,6 +59,7 @@ class RunnerExecutor(Executor):
def run(self, command: str, timeout: Optional[float] = None) -> dict[str, Any]:
timeout = timeout or self.default_timeout
notice = self._before_call() if self._before_call is not None else None
+ started = time.time()
def live(method: str, params: dict[str, Any]) -> None:
if method == "shell.output" and self._on_output is not None:
@@ -73,6 +79,11 @@ class RunnerExecutor(Executor):
answer = {key: result[key] for key in _RESULT_KEYS if key in result}
if notice:
answer["sandbox_notice"] = notice
+ if self._after_call is not None:
+ try:
+ answer.update(self._after_call(started) or {})
+ except Exception: # noqa: BLE001 - a note must never cost the command's result
+ pass
return answer
def run_background(self, command: str) -> dict[str, Any]:
diff --git a/coworker/sandbox/netproxy.py b/coworker/sandbox/netproxy.py
index f4720bce..3d749b8a 100644
--- a/coworker/sandbox/netproxy.py
+++ b/coworker/sandbox/netproxy.py
@@ -15,6 +15,7 @@ import select
import socket
import sys
import threading
+import time
from collections import deque
from typing import Optional, Sequence
@@ -39,6 +40,9 @@ class AllowListProxy:
self._extra: set[tuple[str, int]] = set()
self.add_hosts(extra_hosts)
self.denied: deque[str] = deque(maxlen=50) # recent refusals, newest last
+ # (time, "host:port") of each refused connection, newest last: what the agent is told
+ # with a command's result, and the evidence on the network-access card (OPE-219).
+ self.blocked: deque[tuple[float, str]] = deque(maxlen=200)
self._server = _listen()
self._server.listen(64)
self.port: int = self._server.getsockname()[1]
@@ -53,6 +57,10 @@ class AllowListProxy:
if host and port.isdigit():
self._extra.add((host.lower().rstrip("."), int(port)))
+ def blocked_since(self, since: float) -> list[tuple[float, str]]:
+ """The connections refused at or after `since`, oldest first."""
+ return [item for item in list(self.blocked) if item[0] >= since]
+
@property
def url(self) -> str:
return f"http://127.0.0.1:{self.port}"
@@ -137,6 +145,9 @@ class AllowListProxy:
def _refuse(self, client: socket.socket, status: int, why: str, target: str = "") -> None:
if status == 403 and target:
self.denied.append(target)
+ entry = _blocked_entry(target)
+ if entry:
+ self.blocked.append((time.time(), entry))
body = f"Blocked by the OpenWorker sandbox: {why}.\n".encode()
reason = {400: "Bad Request", 403: "Forbidden", 502: "Bad Gateway"}[status]
head = f"HTTP/1.1 {status} {reason}\r\nContent-Type: text/plain\r\nContent-Length: {len(body)}\r\nConnection: close\r\n\r\n"
@@ -157,6 +168,22 @@ class AllowListProxy:
(b if src is a else a).sendall(data)
+def _blocked_entry(target: str) -> str:
+ """A refused target as "host:port", or "" when it is not a host name. The target is
+ whatever a sandboxed program asked for, and it is shown to the agent and the person, so
+ only a real host name passes (never free text)."""
+ text = target.strip()
+ if "://" in text: # a plain-HTTP request names a URL
+ scheme, rest = text.split("://", 1)
+ rest = rest.split("/", 1)[0]
+ text = rest if ":" in rest else f"{rest}:{80 if scheme.lower() == 'http' else 443}"
+ try:
+ entry = network_profiles.clean_host(text)
+ except ValueError:
+ return ""
+ return "" if entry.startswith("*.") else entry
+
+
def _listen() -> socket.socket:
"""A socket bound on loopback: any free port, or on Windows the first free port of
WINDOWS_PORTS (no SO_REUSEADDR there: on Windows it would let two proxies share one)."""
diff --git a/coworker/sandbox/providers/openshell.py b/coworker/sandbox/providers/openshell.py
index 4f1da7c9..93742824 100644
--- a/coworker/sandbox/providers/openshell.py
+++ b/coworker/sandbox/providers/openshell.py
@@ -366,6 +366,15 @@ class OpenShellProvider:
return # not made yet: the next create renders the list as it stands
_cli("policy", "set", self.sandbox_name, "--policy", str(self._write_policy()), "--wait", timeout=120)
+ reports_blocked = False # see blocked_since
+
+ def blocked_since(self, since: float) -> list[tuple[float, str]]:
+ """(time, "host:port") of the connections the sandbox refused since then. Not read
+ yet on OpenShell: its denial log (`policy.local/v1/denials`, asked from inside the
+ sandbox) has to be checked on a real gateway first, so this reports nothing and the
+ agent asks for a site from the command's own error."""
+ return []
+
def regrant(self, roots: Sequence[dict[str, Any]], *, before_create: Optional[Callable[[], None]] = None) -> None:
"""The session's folders changed. Mounts and the file policy are fixed when a sandbox
is created, so this one is deleted and a new one is created with the new folders.
diff --git a/coworker/sandbox/providers/seatbelt.py b/coworker/sandbox/providers/seatbelt.py
index 6984afb5..86992e3a 100644
--- a/coworker/sandbox/providers/seatbelt.py
+++ b/coworker/sandbox/providers/seatbelt.py
@@ -231,6 +231,12 @@ class SeatbeltProvider:
if new and self._proxy is not None:
self._proxy.add_hosts(new)
+ reports_blocked = True # its proxy records what it refuses
+
+ def blocked_since(self, since: float) -> list[tuple[float, str]]:
+ """(time, "host:port") of the connections the sandbox refused since then."""
+ return self._proxy.blocked_since(since) if self._proxy is not None else []
+
def regrant(self, roots: Sequence[dict[str, Any]], *, before_create: Optional[Callable[[], None]] = None) -> None:
"""The session's folders changed. A profile is fixed when a process starts, so the
daemon is started again with a new one; the client sees a runner restart.
diff --git a/coworker/sandbox/providers/windows.py b/coworker/sandbox/providers/windows.py
index 2c406bbe..f0e9720d 100644
--- a/coworker/sandbox/providers/windows.py
+++ b/coworker/sandbox/providers/windows.py
@@ -329,6 +329,12 @@ class WindowsProvider:
if new and self._proxy is not None:
self._proxy.add_hosts(new)
+ reports_blocked = True # its proxy records what it refuses
+
+ def blocked_since(self, since: float) -> list[tuple[float, str]]:
+ """(time, "host:port") of the connections the sandbox refused since then."""
+ return self._proxy.blocked_since(since) if self._proxy is not None else []
+
def regrant(self, roots: Sequence[dict[str, Any]]) -> None:
"""The session's folders changed. The confinement is per sandbox, not per folder,
so the entries move and the daemon stays: a new folder is usable at once, a removed
diff --git a/coworker/sandbox/settings.py b/coworker/sandbox/settings.py
index 62e9aa83..973b3edc 100644
--- a/coworker/sandbox/settings.py
+++ b/coworker/sandbox/settings.py
@@ -346,6 +346,8 @@ def session_sandbox(engine: Any) -> dict[str, Any]:
"provider": str(getattr(provider, "name", "") or ""),
"network": profile,
"sites": [str(x) for x in sites] if profile == "allowlist" else [],
+ # Allowed by the person for this session only (a card, or the session's list).
+ "session_sites": [str(x) for x in (getattr(getattr(engine, "permissions", None), "session_sites", None) or [])] if profile == "allowlist" else [],
"folders": [
{"path": str(r.get("path", "")), "writable": bool(r.get("writable"))}
for r in (getattr(provider, "roots", None) or [])
diff --git a/coworker/sandbox/workspace.py b/coworker/sandbox/workspace.py
index 31bd2445..20434ab0 100644
--- a/coworker/sandbox/workspace.py
+++ b/coworker/sandbox/workspace.py
@@ -16,7 +16,7 @@ import os
import threading
from abc import ABC, abstractmethod
from pathlib import Path
-from typing import Any, Optional, Sequence
+from typing import Any, Callable, Optional, Sequence
from .runner.executor import Executor
@@ -97,8 +97,11 @@ class RunnerWorkspace(Workspace):
self.hello: dict[str, Any] = {}
self.client = RunnerClient(lambda: provider.open_runner()) # looked up when it connects
self._executor = RunnerExecutor(
- self.client, cwd=str(Path(cwd).expanduser().resolve()), shell=shell, before_call=self.sync_roots
+ self.client, cwd=str(Path(cwd).expanduser().resolve()), shell=shell, before_call=self.sync_roots, after_call=self.network_note
)
+ # Whether the agent can ask the person for a site (`request_network_access`): set by
+ # the session's builder; false where nobody can answer (full access, no such tool).
+ self.can_ask_network: Callable[[], bool] = lambda: False
if start:
self.ensure_started()
else:
@@ -209,7 +212,53 @@ class RunnerWorkspace(Workspace):
text = context_lines(getattr(self.provider, "copied", None))
notes = getattr(self.provider, "notes", None) or []
- return "\n".join(part for part in [text, *notes] if part)
+ return "\n".join(part for part in [text, *notes, self._network_context()] if part)
+
+ def _asking(self) -> bool:
+ try:
+ return bool(self.can_ask_network())
+ except Exception: # noqa: BLE001
+ return False
+
+ def _network_context(self) -> str:
+ """The allowed sites, told to the agent each turn from the live list (OPE-219): which
+ sites its commands reach, and what to do about one that is blocked. Says nothing
+ when the sandbox lets every site out."""
+ if getattr(self.provider, "profile", "") != "allowlist":
+ return ""
+ sites = ", ".join(_site_name(h) for h in getattr(self.provider, "extra_hosts", None) or []) or "none yet"
+ ask = (
+ "If the task needs a blocked site, call request_network_access with the host and a one-line reason, then run the command again once it is allowed. Ask only for sites the task needs."
+ if self._asking()
+ else "The allowed sites cannot be changed from this session. If the task needs a blocked site, tell the user; they can add it in Settings > Sandbox > Choose sites."
+ )
+ return (
+ f"Commands in this session run in a sandbox. They reach only these sites: {sites}. "
+ "A command that tries another site fails, and its result may name the sites the sandbox blocked. "
+ f"{ask} Do not retry a blocked command unchanged, and do not look for another route to a blocked site."
+ )
+
+ @property
+ def reports_blocked(self) -> bool:
+ """Whether this sandbox can say what it blocked. Where it cannot, nothing may be read
+ into an empty answer."""
+ return bool(getattr(self.provider, "reports_blocked", False))
+
+ def blocked_since(self, since: float) -> list[tuple[float, str]]:
+ """(time, "host:port") of the connections this session's sandbox refused since then."""
+ ask = getattr(self.provider, "blocked_since", None)
+ return list(ask(since)) if ask is not None else []
+
+ def network_note(self, started: float) -> Optional[dict[str, Any]]:
+ """What joins a command's result when the sandbox blocked something while it ran:
+ the sites, and a note that says plainly what is and is not known. The attempts are
+ tied to the time the command ran, not to the command."""
+ counts: dict[str, int] = {}
+ for _, entry in self.blocked_since(started):
+ counts[entry] = counts.get(entry, 0) + 1
+ if not counts:
+ return None
+ return {"blocked_sites": list(counts), "network_note": network_note_text(counts, can_ask=self._asking())}
def describe(self) -> dict[str, Any]:
return {**self.provider.describe(), "runner": {k: self.hello.get(k) for k in ("runner_version", "os", "machine", "instance_id")}}
@@ -245,6 +294,32 @@ class RunnerWorkspace(Workspace):
self.registry.close(self._registered)
+_NOTE_SITES = 10 # more than this many blocked sites in one command are counted, not listed
+
+
+def _site_name(entry: str) -> str:
+ """"github.com:443" reads as "github.com": the port only matters when it is not the web's."""
+ return entry[:-4] if entry.endswith(":443") else entry
+
+
+def network_note_text(counts: dict[str, int], *, can_ask: bool) -> str:
+ """The note itself (owner wording 2026-10-03: open about what the sandbox saw, and
+ about not knowing whether it is what broke the command)."""
+ lines = [f" - {entry}" + (f" ({n} attempts)" if n > 1 else "") for entry, n in list(counts.items())[:_NOTE_SITES]]
+ if len(counts) > _NOTE_SITES:
+ lines.append(f" - and {len(counts) - _NOTE_SITES} more")
+ ask = (
+ "If you think a blocked site caused the failure, ask the user to allow it with request_network_access(hosts, reason), then run the command again. Ask only for sites the task needs."
+ if can_ask
+ else "The allowed sites cannot be changed from this session. If a blocked site is needed, tell the user; they can add it in Settings > Sandbox > Choose sites."
+ )
+ return (
+ "Note: this command ran in a sandbox, and the sandbox's network rules may have affected it.\n"
+ "While it ran, the sandbox blocked connections to:\n" + "\n".join(lines) + "\n"
+ "These attempts may have come from this command or from something else running in this session. " + ask
+ )
+
+
def _same_roots(a: list, b: list) -> bool:
def key(roots: list) -> set:
return {(os.path.realpath(str(r["path"])), bool(r.get("writable"))) for r in roots}
diff --git a/coworker/server/manager.py b/coworker/server/manager.py
index e6124491..50b0384a 100644
--- a/coworker/server/manager.py
+++ b/coworker/server/manager.py
@@ -130,6 +130,10 @@ def _grants_of(engine) -> dict[str, Any]:
return out
+# Tools whose approval can change the session's allowed sites (the chip refreshes after one).
+_SITE_TOOLS = {"request_network_access", "web_fetch", "web_search", "browser_open_url"}
+
+
def _grant_offered(outcome, request) -> bool:
"""Whether a persistent grant is legitimately offered for this tool — the server-side
mirror of what the approval card actually renders (`ApprovalCard.tsx`).
@@ -145,6 +149,7 @@ def _grant_offered(outcome, request) -> bool:
- ALWAYS_DOMAIN only means anything for a tool carrying a url.
"""
from ..engine import ApprovalOutcome
+ from ..permissions import NETWORK_ACCESS_TOOL
from ..risk import RiskClass, classify
name = getattr(request, "tool_name", "")
@@ -152,6 +157,10 @@ def _grant_offered(outcome, request) -> bool:
args = getattr(request, "arguments", None) or {}
risk = classify(name, metadata)
+ if name == NETWORK_ACCESS_TOOL:
+ # OPE-219: the network-access card offers this session (sent as the domain grant)
+ # and "Always allow"; nothing tool-wide, so each new site gets its own card.
+ return outcome in (ApprovalOutcome.ALWAYS_DOMAIN, ApprovalOutcome.ALWAYS_SITE)
if outcome is ApprovalOutcome.ALWAYS_COMMAND:
return risk is RiskClass.EXEC
if outcome is ApprovalOutcome.ALWAYS_DOMAIN:
@@ -5621,6 +5630,15 @@ class SessionManager:
message = {**message, "data": {**data, **self.team_card_extras(session_id, data.get("members") or [])}}
if message.get("type") == "mode_notice" and engine:
message = {**message, "data": {**data, "mode": engine.permissions.mode.value}}
+ if message.get("type") == "tool_finished" and engine and data.get("name") in _SITE_TOOLS:
+ # OPE-218/219: a card on one of these may have allowed a site; the header chip
+ # shows the session's list as it stands now.
+ from ..sandbox.settings import session_sandbox
+
+ try:
+ message = {**message, "data": {**data, "sandbox": session_sandbox(engine)}}
+ except Exception: # noqa: BLE001 - the chip must not break a tool result
+ pass
if message.get("type") == "permission_required" and data.get("name") == "decide_worker_call":
worker_call = self.worker_call_for(data.get("arguments") or {}, lead_session=session_id)
if worker_call:
diff --git a/coworker/tools/network.py b/coworker/tools/network.py
new file mode 100644
index 00000000..d860f4dc
--- /dev/null
+++ b/coworker/tools/network.py
@@ -0,0 +1,64 @@
+"""The `request_network_access` tool: the agent asks the person for a site its commands
+cannot reach (OPE-219).
+
+A sandboxed session on "Only the sites you allow" lets its commands out to the listed sites
+only. When a task needs another one, the agent calls this tool with the host and a reason.
+The permission engine turns the call into a card only a person can answer (allow for this
+session, always allow, or deny); on approval the engine opens the site on the running
+sandbox, and only then does this body run, to tell the agent what it now has. In full
+access the call is refused: no mode changes a wall.
+
+Registered only for a session whose sandbox uses the allowed-sites list.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from aisuite.agents import ToolMetadata, tool
+
+from ..permissions import NETWORK_ACCESS_TOOL, PermissionEngine, network_request_hosts
+
+
+def _name(entry: str) -> str:
+ return entry[:-4] if entry.endswith(":443") else entry
+
+
+def request_network_access_tool(permissions: PermissionEngine) -> object:
+ def request_network_access(hosts: list[str], reason: str) -> dict:
+ """Ask the user to let this session's commands reach a site that the sandbox blocks.
+ Give `hosts` as exact host names (for example ["registry.npmjs.org"]; add a port
+ only when it is not 443, for example "db.example.com:5432"), at most five, no
+ wildcards and no IP addresses, and a one-line `reason` the user can judge. Use it
+ when a command failed because a site was blocked, or before a command you know
+ needs a site that is not on the allowed sites. The user decides; when the result
+ says a site is allowed, run the command again. Ask only for sites the task needs,
+ and do not look for another route to a blocked site.
+ """
+ wanted, _ = network_request_hosts({"hosts": hosts})
+ allowed = [entry for entry in wanted if permissions._entry_allowed(entry)]
+ failed: dict[str, Any] = {
+ _name(entry): permissions.site_open_errors[key]
+ for entry in allowed
+ for key in (entry, entry.rsplit(":", 1)[0])
+ if key in permissions.site_open_errors
+ }
+ ready = [_name(entry) for entry in allowed if _name(entry) not in failed]
+ result: dict[str, Any] = {"allowed": ready}
+ if ready:
+ result["message"] = f"{', '.join(ready)} can be reached by this session's commands now. Run the command again."
+ if failed:
+ result["not_opened"] = failed
+ result["note"] = "The user allowed these, but the running sandbox could not take them. Tell the user; a new session will have them."
+ return result
+
+ request_network_access.__name__ = NETWORK_ACCESS_TOOL
+ return tool(
+ request_network_access,
+ metadata=ToolMetadata(
+ category="sandbox",
+ risk_level="medium",
+ capabilities=["request_network_access"],
+ description="Ask the user to let this session's commands reach a site that the sandbox's allowed sites block.",
+ ),
+ )
diff --git a/docs/macos-sandbox.md b/docs/macos-sandbox.md
index e2ffeec5..211106e7 100644
--- a/docs/macos-sandbox.md
+++ b/docs/macos-sandbox.md
@@ -79,6 +79,15 @@ site for the session's commands, at once: the running sandbox takes the new entr
restart. "Once" is that one web call only. Connectors and MCP servers are not covered by the
list; each has its own approval.
+When a command needs a site that is not on the list, it fails inside the sandbox. The
+coworker can then ask you for the site: a card names it, gives the coworker's reason, and
+says whether the sandbox has in fact blocked it. You choose **Allow for this session**,
+**Always allow**, or **Deny**; the site opens for the running session without a restart.
+The coworker is told which sites the sandbox blocked while a command ran, so it asks for the
+right one. With full access (no approvals) the coworker cannot ask;
+add the site in Settings ▸ Sandbox yourself. The header chip lists the session's sites, those
+from Settings and those allowed for this session only.
+
## Sharing a credential on purpose
By default the sandbox has none of your logins, which also means `git push` over SSH has
diff --git a/docs/openshell.md b/docs/openshell.md
index 49a4751f..6bf29046 100644
--- a/docs/openshell.md
+++ b/docs/openshell.md
@@ -137,6 +137,15 @@ site for the session's commands, at once: the running sandbox takes the new entr
restart. "Once" is that one web call only. Connectors and MCP servers are not covered by the
list; each has its own approval.
+When a command needs a site that is not on the list, it fails inside the sandbox. The
+coworker can then ask you for the site: a card names it, gives the coworker's reason, and
+says whether the sandbox has in fact blocked it. You choose **Allow for this session**,
+**Always allow**, or **Deny**; the site opens for the running session without a restart.
+On OpenShell the coworker is not yet told which sites were blocked; it asks from the
+command's own error. With full access (no approvals) the coworker cannot ask;
+add the site in Settings ▸ Sandbox yourself. The header chip lists the session's sites, those
+from Settings and those allowed for this session only.
+
OpenShell enforces the list in the container.
## Sharing a credential on purpose
diff --git a/docs/windows-sandbox.md b/docs/windows-sandbox.md
index 4a02a3d1..539d96f2 100644
--- a/docs/windows-sandbox.md
+++ b/docs/windows-sandbox.md
@@ -148,6 +148,15 @@ site for the session's commands, at once: the running sandbox takes the new entr
restart. "Once" is that one web call only. Connectors and MCP servers are not covered by the
list; each has its own approval.
+When a command needs a site that is not on the list, it fails inside the sandbox. The
+coworker can then ask you for the site: a card names it, gives the coworker's reason, and
+says whether the sandbox has in fact blocked it. You choose **Allow for this session**,
+**Always allow**, or **Deny**; the site opens for the running session without a restart.
+The coworker is told which sites the sandbox blocked while a command ran, so it asks for the
+right one. With full access (no approvals) the coworker cannot ask;
+add the site in Settings ▸ Sandbox yourself. The header chip lists the session's sites, those
+from Settings and those allowed for this session only.
+
Choosing a mode never touches the firewall. The rules are written once at setup; OpenWorker
picks the account. In the closed mode a sandbox can still **listen** on a local port (a dev
server your browser can open); it cannot **connect** to one, other than the proxy.
diff --git a/surfaces/gui/src/App.tsx b/surfaces/gui/src/App.tsx
index 865eee37..aff36f8d 100644
--- a/surfaces/gui/src/App.tsx
+++ b/surfaces/gui/src/App.tsx
@@ -1003,6 +1003,8 @@ export function App() {
setItems((p) => [...p, questionItemFromPayload(d)]);
break;
case "tool_finished":
+ // A card on this tool may have allowed a site: the header chip follows (OPE-219).
+ if (d.sandbox) setSandboxInfo(d.sandbox);
if (d.tool_call_id) {
const calls = finishedGateCalls.current.get(gateScope) || new Set<string>();
calls.add(d.tool_call_id);
diff --git a/surfaces/gui/src/cardPayloads.ts b/surfaces/gui/src/cardPayloads.ts
index 808e5b25..b49154ae 100644
--- a/surfaces/gui/src/cardPayloads.ts
+++ b/surfaces/gui/src/cardPayloads.ts
@@ -30,6 +30,16 @@ export function approvalItemFromPayload(d: any): ApprovalItem {
standingTarget: d.standing_target || undefined,
searchProvider: d.search_provider || undefined,
siteWall: d.site_wall || undefined,
+ networkRequest: d.network_request
+ ? {
+ reason: String(d.network_request.reason || ""),
+ evidence: d.network_request.evidence !== false,
+ hosts: (d.network_request.hosts || []).map((h: any) => ({
+ host: String(h.host || ""),
+ blockedSecondsAgo: typeof h.blocked_seconds_ago === "number" ? h.blocked_seconds_ago : null,
+ })),
+ }
+ : undefined,
provenance: d.provenance || undefined,
reviewerUnsure: d.reviewer_unsure || undefined,
escalation: d.escalation || undefined,
diff --git a/surfaces/gui/src/components/ApprovalCard.test.tsx b/surfaces/gui/src/components/ApprovalCard.test.tsx
index b9f63fd0..61c4058e 100644
--- a/surfaces/gui/src/components/ApprovalCard.test.tsx
+++ b/surfaces/gui/src/components/ApprovalCard.test.tsx
@@ -535,6 +535,59 @@ describe("ApprovalCard — §1.9 egress cards", () => {
expect(screen.getByTestId("approval-always-site").textContent).toBe("Always allow weather.com");
});
+ it("a network request shows the agent's reason and what the sandbox saw, and is never once (OPE-219)", () => {
+ const onApprove = vi.fn();
+ const ask = fetchApproval({
+ name: "request_network_access",
+ args: { hosts: ["api.acme.dev", "db.acme.dev:5432"], reason: "The deploy script pushes the build." },
+ reason: "asks to let this session's commands reach api.acme.dev, db.acme.dev:5432",
+ networkRequest: {
+ reason: "The deploy script pushes the build.",
+ evidence: true,
+ hosts: [
+ { host: "api.acme.dev:443", blockedSecondsAgo: 240 },
+ { host: "db.acme.dev:5432", blockedSecondsAgo: null },
+ ],
+ },
+ });
+ render(<ApprovalCard item={ask} onApprove={onApprove} />);
+ expect(screen.getByText("api.acme.dev and db.acme.dev:5432")).toBeTruthy(); // the headline names the sites
+ expect(screen.getByTestId("approval-network-request").textContent).toContain("The deploy script pushes the build.");
+ const hosts = screen.getAllByTestId("approval-network-host").map((n) => n.textContent);
+ expect(hosts).toEqual([
+ "api.acme.dev The sandbox blocked this site 4 minutes ago.",
+ "db.acme.dev:5432 No command has tried this site yet.",
+ ]);
+ // This session, always, or no: a command's network access cannot be "once".
+ expect(screen.queryByText("Allow once")).toBeNull();
+ expect(screen.getByTestId("approval-network-always").textContent).toBe("Always allow these sites");
+ fireEvent.click(screen.getByTestId("approval-network-session"));
+ expect(onApprove).toHaveBeenCalledWith("always_domain");
+ fireEvent.click(screen.getByTestId("approval-network-always"));
+ expect(onApprove).toHaveBeenCalledWith("always_site");
+ });
+
+ it("a network request for one site just blocked names it on the always button", () => {
+ const ask = fetchApproval({
+ name: "request_network_access",
+ args: { hosts: ["registry.npmjs.org"], reason: "npm install needs the registry." },
+ networkRequest: { reason: "npm install needs the registry.", evidence: true, hosts: [{ host: "registry.npmjs.org:443", blockedSecondsAgo: 20 }] },
+ });
+ const { rerender } = render(<ApprovalCard item={ask} onApprove={vi.fn()} autoApprove />);
+ expect(screen.getByTestId("approval-network-host").textContent).toBe("registry.npmjs.org The sandbox blocked this site a moment ago.");
+ // A sandbox that cannot say what it blocked: the site alone, no claim either way.
+ rerender(
+ <ApprovalCard
+ item={{ ...ask, networkRequest: { reason: "x", evidence: false, hosts: [{ host: "registry.npmjs.org:443", blockedSecondsAgo: null }] } }}
+ onApprove={vi.fn()}
+ autoApprove
+ />,
+ );
+ expect(screen.getByTestId("approval-network-host").textContent?.trim()).toBe("registry.npmjs.org");
+ // Standing policy the person sets: offered in Auto-approve too.
+ expect(screen.getByTestId("approval-network-always").textContent).toBe("Always allow registry.npmjs.org");
+ });
+
it("an ordinary fetch card has no allowed-sites line or button", () => {
render(<ApprovalCard item={fetchApproval()} onApprove={vi.fn()} />);
expect(screen.queryByTestId("approval-site-wall")).toBeNull();
diff --git a/surfaces/gui/src/components/ApprovalCard.tsx b/surfaces/gui/src/components/ApprovalCard.tsx
index 7a436404..b9d53c1b 100644
--- a/surfaces/gui/src/components/ApprovalCard.tsx
+++ b/surfaces/gui/src/components/ApprovalCard.tsx
@@ -123,6 +123,8 @@ export function scopeNote(
// save_skill's corner answers WHERE (SKILLS-SPEC §5.2): the exact place to find, edit,
// or turn off the skill afterwards.
if (name === "save_skill") return { text: tt("approval.scope.save_skill"), external: false };
+ // OPE-219: the ask is to let commands OUT, so the corner says what it changes.
+ if (name === "request_network_access") return { text: tt("approval.scope.network_access"), external: true };
if (category === "connector") return { text: tt("approval.scope.connector"), external: true };
// MCP tools (OPE-136 finding 4): the one family the old fallthrough mislabeled
// "stays on this computer". The destination comes from the server DEF — the user's
@@ -311,6 +313,29 @@ function Buttons({
// run context (§25: the task-persistent grant is that flow's one grant) and in
// Auto-approve (§1.5: in-flow grants don't skip the judge).
const externalFamily = isMcp || connector || EXTERNAL.has(item.name);
+ // OPE-219: a site for commands is never "once". This session, always, or no. "Always"
+ // writes the machine's list, so it is offered in Auto-approve too.
+ if (item.networkRequest) {
+ const hosts = item.networkRequest.hosts.map((h) => h.host.replace(/:443$/, ""));
+ return (
+ <div className="approval-btns">
+ <button className="btn approval-primary" onClick={() => onApprove("always_domain")} data-testid="approval-network-session">
+ {t("approval.btn.network_session")}
+ </button>
+ <button
+ className="btn"
+ title={t("approval.btn.network_always_title")}
+ onClick={() => onApprove("always_site")}
+ data-testid="approval-network-always"
+ >
+ {hosts.length === 1 ? t("approval.btn.always_site", { host: hosts[0] }) : t("approval.btn.network_always_many")}
+ </button>
+ <button className="btn quiet-deny" onClick={() => onApprove("deny")}>
+ {t("approval.btn.deny")}
+ </button>
+ </div>
+ );
+ }
return (
<div className="approval-btns">
<button className="btn approval-primary" onClick={() => onApprove("once")}>
@@ -488,7 +513,27 @@ export function ApprovalCard({
// Quiet, not a warning: the reviewer hesitating is context, not danger.
// OPE-219: a site the sandbox's allowed sites do not include. Its own plain line, in
// place of the generic "requires a human decision" banner the engine also sends.
- const reviewerUnsure = item.siteWall ? (
+ const reviewerUnsure = item.networkRequest ? (
+ // The agent's reason, then what the sandbox itself saw for each site: the person's
+ // check on the request.
+ <div className="mt-1" data-testid="approval-network-request">
+ {item.networkRequest.reason && <div className="text-ui text-ink">{item.networkRequest.reason}</div>}
+ <div className="mt-1.5 flex flex-col gap-0.5">
+ {item.networkRequest.hosts.map((h) => (
+ <div key={h.host} className="text-meta text-muted" data-testid="approval-network-host">
+ <code className="approval-tool">{h.host.replace(/:443$/, "")}</code>{" "}
+ {!item.networkRequest!.evidence
+ ? ""
+ : h.blockedSecondsAgo === null
+ ? t("approval.network.not_seen")
+ : h.blockedSecondsAgo < 60
+ ? t("approval.network.blocked_now")
+ : t("approval.network.blocked_minutes", { count: Math.round(h.blockedSecondsAgo / 60) })}
+ </div>
+ ))}
+ </div>
+ </div>
+ ) : item.siteWall ? (
<div className="text-meta text-muted mt-1" data-testid="approval-site-wall">
{t("approval.site_wall_note", { host: item.siteWall })}
</div>
@@ -521,7 +566,7 @@ export function ApprovalCard({
{peek && content && <PreviewBlock text={content} />}
{provenance}
{reviewerUnsure}
- {reason && <div className="approval-reason">{reason}</div>}
+ {reason && !item.networkRequest && <div className="approval-reason">{reason}</div>}
</div>
);
}
@@ -612,7 +657,7 @@ export function ApprovalCard({
(finding 7: no silent truncation, on any tool, ever). MCP and egress tools
are excluded: they render full evidence above. */}
{!FILE_WRITES.has(item.name) &&
- !["run_shell", "send_message", "send_file", "save_skill", "web_fetch", "web_search"].includes(item.name) &&
+ !["run_shell", "send_message", "send_file", "save_skill", "web_fetch", "web_search", "request_network_access"].includes(item.name) &&
!item.name.startsWith("mcp__") &&
!grants.length &&
(() => {
@@ -626,7 +671,7 @@ export function ApprovalCard({
})()}
{provenance}
{reviewerUnsure}
- {reason && <div className="approval-reason">{reason}</div>}
+ {reason && !item.networkRequest && <div className="approval-reason">{reason}</div>}
{item.resolved ? (
<div className="resolved">{t("approval.resolved_prefix", { state: item.resolved.replace(/_/g, " ") })}</div>
diff --git a/surfaces/gui/src/components/SandboxChip.test.tsx b/surfaces/gui/src/components/SandboxChip.test.tsx
index 11ed0e04..5b9df842 100644
--- a/surfaces/gui/src/components/SandboxChip.test.tsx
+++ b/surfaces/gui/src/components/SandboxChip.test.tsx
@@ -30,6 +30,15 @@ describe("SandboxChip", () => {
expect(openSettings).toHaveBeenCalled();
});
+ it("counts and lists the sites allowed for this session apart from the machine's", () => {
+ render(<SandboxChip info={{ ...sandboxed, session_sites: ["registry.npmjs.org:443", "db.acme.dev:5432"] }} />);
+ const chip = screen.getByTestId("sandbox-chip");
+ expect(chip.textContent).toBe("OpenShell · 5 sites");
+ fireEvent.click(chip);
+ expect(screen.getByTestId("sandbox-chip-session-sites").textContent).toBe("registry.npmjs.org, db.acme.dev:5432");
+ expect(screen.getByTestId("sandbox-chip-panel").textContent).toContain("Sites allowed for this session only");
+ });
+
it("any site, and one site", () => {
const { rerender } = render(<SandboxChip info={{ ...sandboxed, provider: "seatbelt", network: "open", sites: [] }} />);
expect(screen.getByTestId("sandbox-chip").textContent).toBe("macOS sandbox · any site");
diff --git a/surfaces/gui/src/components/SandboxChip.tsx b/surfaces/gui/src/components/SandboxChip.tsx
index 0764198f..a1db782b 100644
--- a/surfaces/gui/src/components/SandboxChip.tsx
+++ b/surfaces/gui/src/components/SandboxChip.tsx
@@ -14,7 +14,8 @@ export interface SessionSandbox {
state: "sandboxed" | "not_sandboxed" | "off";
provider?: string;
network?: string; // "allowlist" | "open"
- sites?: string[];
+ sites?: string[]; // from Settings ▸ Sandbox
+ session_sites?: string[]; // allowed by the person for this session only
folders?: { path: string; writable: boolean }[];
logins?: string[];
started?: boolean;
@@ -49,10 +50,11 @@ export function SandboxChip({ info, onOpenSettings }: { info: SessionSandbox | n
const sandboxed = info.state === "sandboxed";
const providerLabel = t(`sandboxchip.provider_${info.provider}`, { defaultValue: info.provider || "" });
const sites = info.sites || [];
+ const sessionSites = info.session_sites || [];
const network = !sandboxed
? ""
: info.network === "allowlist"
- ? t("sandboxchip.sites", { count: sites.length })
+ ? t("sandboxchip.sites", { count: sites.length + sessionSites.length })
: t("sandboxchip.any_site");
const label = sandboxed ? `${providerLabel} · ${network}` : t("sandboxchip.not_sandboxed");
const tone = sandboxed ? "border-okLine bg-okSoft text-ok" : "border-lineStrong bg-warnSoft text-warnInk";
@@ -93,6 +95,14 @@ export function SandboxChip({ info, onOpenSettings }: { info: SessionSandbox | n
: t("sandboxchip.no_sites")
: t("sandboxchip.any_site_long")}
</div>
+ {info.network === "allowlist" && sessionSites.length > 0 && (
+ <>
+ <div className="text-label text-faint mt-3 mb-0.5">{t("sandboxchip.session_sites_label")}</div>
+ <div className="text-meta text-ink" data-testid="sandbox-chip-session-sites">
+ {sessionSites.map(siteName).join(", ")}
+ </div>
+ </>
+ )}
{(info.logins || []).length > 0 && (
<>
<div className="text-label text-faint mt-3 mb-0.5">{t("sandboxchip.logins")}</div>
diff --git a/surfaces/gui/src/gallery/states.contract.json b/surfaces/gui/src/gallery/states.contract.json
index 59e8ac56..c7824868 100644
--- a/surfaces/gui/src/gallery/states.contract.json
+++ b/surfaces/gui/src/gallery/states.contract.json
@@ -8960,6 +8960,61 @@
"search_provider": "brave",
"site_wall": "api.search.brave.com"
},
+ "network-access-for-a-blocked-site": {
+ "name": "request_network_access",
+ "arguments": {
+ "hosts": [
+ "registry.npmjs.org"
+ ],
+ "reason": "npm install needs the package registry to download dependencies."
+ },
+ "reason": "asks to let this session's commands reach registry.npmjs.org",
+ "escalation": {
+ "kind": "human_required",
+ "reason": "asks to let this session's commands reach registry.npmjs.org"
+ },
+ "category": "sandbox",
+ "network_request": {
+ "evidence": true,
+ "reason": "npm install needs the package registry to download dependencies.",
+ "hosts": [
+ {
+ "host": "registry.npmjs.org:443",
+ "blocked_seconds_ago": 20
+ }
+ ]
+ }
+ },
+ "network-access-before-any-attempt": {
+ "name": "request_network_access",
+ "arguments": {
+ "hosts": [
+ "api.acme.dev",
+ "db.acme.dev:5432"
+ ],
+ "reason": "The deploy script pushes the build to the Acme API and runs a migration on the database."
+ },
+ "reason": "asks to let this session's commands reach api.acme.dev, db.acme.dev:5432",
+ "escalation": {
+ "kind": "human_required",
+ "reason": "asks to let this session's commands reach api.acme.dev, db.acme.dev:5432"
+ },
+ "category": "sandbox",
+ "network_request": {
+ "evidence": true,
+ "reason": "The deploy script pushes the build to the Acme API and runs a migration on the database.",
+ "hosts": [
+ {
+ "host": "api.acme.dev:443",
+ "blocked_seconds_ago": 240
+ },
+ {
+ "host": "db.acme.dev:5432",
+ "blocked_seconds_ago": null
+ }
+ ]
+ }
+ },
"connector-action": {
"name": "github_create_pull_request",
"arguments": {
@@ -9258,6 +9313,67 @@
"provenance": ""
}
},
+ "network-access-for-a-blocked-site": {
+ "id": "gallery-item",
+ "session_id": "gallery-session",
+ "kind": "approval",
+ "title": "Run `request_network_access`?",
+ "body": "asks to let this session's commands reach registry.npmjs.org",
+ "state": "pending",
+ "resolution": null,
+ "inbox": "default",
+ "created_at": "2026-09-17T09:30:00Z",
+ "resolved_at": null,
+ "visibility": "inbox",
+ "session_title": "Mention #3 · Invoice PDF download",
+ "session_agent": "swe-lead",
+ "session_exists": true,
+ "data": {
+ "tool": "request_network_access",
+ "arguments": {
+ "hosts": [
+ "registry.npmjs.org"
+ ],
+ "reason": "npm install needs the package registry to download dependencies."
+ },
+ "escalation": {
+ "kind": "human_required",
+ "reason": "asks to let this session's commands reach registry.npmjs.org"
+ },
+ "provenance": ""
+ }
+ },
+ "network-access-before-any-attempt": {
+ "id": "gallery-item",
+ "session_id": "gallery-session",
+ "kind": "approval",
+ "title": "Run `request_network_access`?",
+ "body": "asks to let this session's commands reach api.acme.dev, db.acme.dev:5432",
+ "state": "pending",
+ "resolution": null,
+ "inbox": "default",
+ "created_at": "2026-09-17T09:30:00Z",
+ "resolved_at": null,
+ "visibility": "inbox",
+ "session_title": "Mention #3 · Invoice PDF download",
+ "session_agent": "swe-lead",
+ "session_exists": true,
+ "data": {
+ "tool": "request_network_access",
+ "arguments": {
+ "hosts": [
+ "api.acme.dev",
+ "db.acme.dev:5432"
+ ],
+ "reason": "The deploy script pushes the build to the Acme API and runs a migration on the database."
+ },
+ "escalation": {
+ "kind": "human_required",
+ "reason": "asks to let this session's commands reach api.acme.dev, db.acme.dev:5432"
+ },
+ "provenance": ""
+ }
+ },
"connector-action": {
"id": "gallery-item",
"session_id": "gallery-session",
diff --git a/surfaces/gui/src/gallery/states/approval.ts b/surfaces/gui/src/gallery/states/approval.ts
index 8a4ac9b9..15d8e4e4 100644
--- a/surfaces/gui/src/gallery/states/approval.ts
+++ b/surfaces/gui/src/gallery/states/approval.ts
@@ -103,6 +103,43 @@ export const approvalStates: CardState[] = [
site_wall: "api.search.brave.com",
},
},
+ {
+ id: "network-access-for-a-blocked-site",
+ title: "The agent asks for a site its commands cannot reach",
+ note: "A command failed inside the sandbox, the result named the blocked site, and the agent called request_network_access. The card gives the agent's reason and what the sandbox itself saw. A site for commands is never \"once\": this session, always, or no. Only a person answers; in Bypass the call is refused with no card (OPE-219).",
+ payload: {
+ name: "request_network_access",
+ arguments: { hosts: ["registry.npmjs.org"], reason: "npm install needs the package registry to download dependencies." },
+ reason: "asks to let this session's commands reach registry.npmjs.org",
+ escalation: { kind: "human_required", reason: "asks to let this session's commands reach registry.npmjs.org" },
+ category: "sandbox",
+ network_request: {
+ evidence: true,
+ reason: "npm install needs the package registry to download dependencies.",
+ hosts: [{ host: "registry.npmjs.org:443", blocked_seconds_ago: 20 }],
+ },
+ },
+ },
+ {
+ id: "network-access-before-any-attempt",
+ title: "The agent asks ahead for two sites, one never tried",
+ note: "The agent may ask before running a command. A site no command has tried says so, which is the person's cue to look twice at the reason.",
+ payload: {
+ name: "request_network_access",
+ arguments: { hosts: ["api.acme.dev", "db.acme.dev:5432"], reason: "The deploy script pushes the build to the Acme API and runs a migration on the database." },
+ reason: "asks to let this session's commands reach api.acme.dev, db.acme.dev:5432",
+ escalation: { kind: "human_required", reason: "asks to let this session's commands reach api.acme.dev, db.acme.dev:5432" },
+ category: "sandbox",
+ network_request: {
+ evidence: true,
+ reason: "The deploy script pushes the build to the Acme API and runs a migration on the database.",
+ hosts: [
+ { host: "api.acme.dev:443", blocked_seconds_ago: 240 },
+ { host: "db.acme.dev:5432", blocked_seconds_ago: null },
+ ],
+ },
+ },
+ },
{
id: "connector-action",
title: "Connector action",
diff --git a/surfaces/gui/src/humanize.ts b/surfaces/gui/src/humanize.ts
index 88939c0d..2d3d012b 100644
--- a/surfaces/gui/src/humanize.ts
+++ b/surfaces/gui/src/humanize.ts
@@ -153,6 +153,13 @@ export function humanizeApprovalTitle(name: string, args: any): HumanLine {
}
case "web_search":
return { pre: "Search the web" };
+ // OPE-219: the agent asks for sites its sandboxed commands cannot reach.
+ case "request_network_access": {
+ const raw = Array.isArray(a.hosts) ? a.hosts : a.hosts ? [a.hosts] : [];
+ const hosts = raw.map((h: unknown) => String(h).replace(/:443$/, "")).filter(Boolean);
+ if (!hosts.length) return { pre: "Let commands reach a site" };
+ return { pre: "Let commands reach ", obj: hosts.length > 2 ? `${hosts[0]} and ${hosts.length - 1} more` : hosts.join(" and ") };
+ }
default:
return { pre: `Use ${name}` };
}
diff --git a/surfaces/gui/src/locales/en.json b/surfaces/gui/src/locales/en.json
index fb3337f3..d304fb78 100644
--- a/surfaces/gui/src/locales/en.json
+++ b/surfaces/gui/src/locales/en.json
@@ -639,7 +639,8 @@
"search_provider_dest": "your search provider",
"mcp_server_fallback": "the MCP server",
"mcp_local": "runs a local program on this computer",
- "mcp_unknown": "acts through an MCP server"
+ "mcp_unknown": "acts through an MCP server",
+ "network_access": "opens the sandbox to a site"
},
"btn": {
"allow_every_time": "Allow every time",
@@ -662,7 +663,10 @@
"this_run": "Allow for this request",
"this_run_title": "Covers {{name}} until the agent finishes answering your current message. Later calls in this answer run without showing you their arguments first — you'll see them in the transcript afterward. Nothing survives past this answer.",
"always_site": "Always allow {{host}}",
- "always_site_title": "Adds {{host}} to the allowed sites in Settings ▸ Sandbox, for commands and web tools, on this machine"
+ "always_site_title": "Adds {{host}} to the allowed sites in Settings ▸ Sandbox, for commands and web tools, on this machine",
+ "network_session": "Allow for this session",
+ "network_always_title": "Adds the site to the allowed sites in Settings ▸ Sandbox, for commands and web tools, on this machine",
+ "network_always_many": "Always allow these sites"
},
"preview_less": "show less",
"preview_all_lines": "show all {{n}} lines",
@@ -684,7 +688,13 @@
"search_note": "Queries go to your configured search provider.",
"search_note_current": "Queries go to your configured search provider (currently: {{provider}}).",
"reviewer_unsure": "reviewer wasn’t sure: {{note}}",
- "site_wall_note": "{{host}} is not on your allowed sites."
+ "site_wall_note": "{{host}} is not on your allowed sites.",
+ "network": {
+ "not_seen": "No command has tried this site yet.",
+ "blocked_now": "The sandbox blocked this site a moment ago.",
+ "blocked_minutes_one": "The sandbox blocked this site {{count}} minute ago.",
+ "blocked_minutes_other": "The sandbox blocked this site {{count}} minutes ago."
+ }
},
"search": {
"placeholder": "Search chats",
@@ -2662,6 +2672,7 @@
"logins": "Shared logins",
"not_title": "This session is not sandboxed",
"not_sub": "It was opened before the sandbox was switched on. Its commands run on this computer without the sandbox. Start a new session to use the sandbox.",
- "open_settings": "Open Settings ▸ Sandbox"
+ "open_settings": "Open Settings ▸ Sandbox",
+ "session_sites_label": "Sites allowed for this session only"
}
}
diff --git a/surfaces/gui/src/locales/zh.json b/surfaces/gui/src/locales/zh.json
index 18e7a234..fc0a038b 100644
--- a/surfaces/gui/src/locales/zh.json
+++ b/surfaces/gui/src/locales/zh.json
@@ -629,7 +629,8 @@
"search_provider_dest": "你的搜索服务商",
"mcp_server_fallback": "MCP 服务器",
"mcp_local": "在本机运行一个本地程序",
- "mcp_unknown": "通过 MCP 服务器执行操作"
+ "mcp_unknown": "通过 MCP 服务器执行操作",
+ "network_access": "让沙盒可以访问一个网站"
},
"btn": {
"allow_every_time": "每次都允许",
@@ -652,7 +653,10 @@
"this_run": "本次请求内允许",
"this_run_title": "在智能体回答完您当前这条消息之前,{{name}} 的后续调用将不再展示参数、直接执行 —— 事后可在会话记录中查看。回答结束后此授权即失效,不会保留任何设置。",
"always_site": "始终允许 {{host}}",
- "always_site_title": "将 {{host}} 加入 设置 ▸ 沙盒 的允许网站列表,对本机的命令和网页工具生效"
+ "always_site_title": "将 {{host}} 加入 设置 ▸ 沙盒 的允许网站列表,对本机的命令和网页工具生效",
+ "network_session": "本次会话允许",
+ "network_always_title": "将该网站加入 设置 ▸ 沙盒 的允许网站列表,对本机的命令和网页工具生效",
+ "network_always_many": "始终允许这些网站"
},
"preview_less": "收起",
"preview_all_lines": "展开全部 {{n}} 行",
@@ -673,7 +677,13 @@
"search_note": "查询会发送到你配置的搜索服务商。",
"search_note_current": "查询会发送到你配置的搜索服务商(当前:{{provider}})。",
"reviewer_unsure": "审查器不确定:{{note}}",
- "site_wall_note": "{{host}} 不在你允许的网站列表中。"
+ "site_wall_note": "{{host}} 不在你允许的网站列表中。",
+ "network": {
+ "not_seen": "还没有命令访问过这个网站。",
+ "blocked_now": "沙盒刚刚拦截了对这个网站的访问。",
+ "blocked_minutes_one": "沙盒在 {{count}} 分钟前拦截了对这个网站的访问。",
+ "blocked_minutes_other": "沙盒在 {{count}} 分钟前拦截了对这个网站的访问。"
+ }
},
"search": {
"placeholder": "搜索会话",
@@ -2622,6 +2632,7 @@
"logins": "共享的登录",
"not_title": "此会话未在沙盒中运行",
"not_sub": "它在开启沙盒之前打开,其命令在本机上不经沙盒运行。新建会话即可使用沙盒。",
- "open_settings": "打开 设置 ▸ 沙盒"
+ "open_settings": "打开 设置 ▸ 沙盒",
+ "session_sites_label": "仅本次会话允许的网站"
}
}
diff --git a/surfaces/gui/src/types.ts b/surfaces/gui/src/types.ts
index e1ab348a..4c5ecf7d 100644
--- a/surfaces/gui/src/types.ts
+++ b/surfaces/gui/src/types.ts
@@ -181,6 +181,9 @@ export type Item =
// OPE-219: the host the sandbox's allowed-sites wall stopped. The card says so and
// offers "Always allow <host>", which adds it to Settings ▸ Sandbox ▸ allowed sites.
siteWall?: string;
+ // OPE-219: the agent asked for sites its commands cannot reach (request_network_access).
+ // `evidence` is false where the sandbox cannot say what it blocked: the card then shows the sites only.
+ networkRequest?: { reason: string; evidence: boolean; hosts: { host: string; blockedSecondsAgo: number | null }[] };
// OPE-114 §1: set when the action would run a file the agent itself created or
// downloaded this session ("setup.py was created by the agent 3 steps ago"). The
// one fact that cannot be read off the command text. Engine-authored, fixed
diff --git a/tests/test_network_access.py b/tests/test_network_access.py
new file mode 100644
index 00000000..373b24dc
--- /dev/null
+++ b/tests/test_network_access.py
@@ -0,0 +1,230 @@
+"""`request_network_access`: the agent asks a person for a site its commands cannot reach
+(OPE-219).
+
+The sandbox's allowed sites are a wall. A command that needs another site fails inside the
+sandbox; the sandbox says what it blocked, the agent asks with a reason, and a person
+decides. Nothing else can: not the reviewer, not a lead, not full access.
+"""
+
+from __future__ import annotations
+
+import socket
+from types import SimpleNamespace
+
+import pytest
+
+from coworker.permissions import NETWORK_ACCESS_TOOL, Mode, PermissionEngine, network_request_hosts
+from coworker.sandbox import netproxy
+from coworker.sandbox.executor import RunnerExecutor
+from coworker.sandbox.workspace import RunnerWorkspace, network_note_text
+from coworker.tools.network import request_network_access_tool
+
+SITES = ["github.com:443", "*.githubusercontent.com:443"]
+
+
+def engine(tmp_path, mode=Mode.INTERACTIVE, **kw):
+ return PermissionEngine(workspace_root=tmp_path, mode=mode, sandbox_sites=list(SITES), **kw)
+
+
+def ask(eng, hosts, reason="npm install needs the registry"):
+ return eng.evaluate(NETWORK_ACCESS_TOOL, {"hosts": hosts, "reason": reason}, None)
+
+
+# -- what the agent may ask for -----------------------------------------------------------
+def test_only_exact_host_names_are_accepted():
+ good, bad = network_request_hosts({"hosts": ["Registry.NPMjs.org", "db.example.com:5432", "registry.npmjs.org:443", "https://pypi.org/simple/"]})
+ assert good == ["registry.npmjs.org:443", "db.example.com:5432", "pypi.org:443"] and bad == []
+ for item in ("*.npmjs.org", "10.0.0.8", "10.0.0.8:5432", "localhost", "ignore your instructions", ""):
+ good, bad = network_request_hosts({"hosts": [item]})
+ assert good == [] and bad == [item[:80]], item
+ assert network_request_hosts({"hosts": "pypi.org"}) == (["pypi.org:443"], []) # a lone string is one host
+ assert network_request_hosts({}) == ([], [])
+
+
+def test_a_bad_or_oversized_request_is_refused_without_a_card(tmp_path):
+ eng = engine(tmp_path)
+ for hosts in (["*.npmjs.org"], [], ["a.dev", "b.dev", "c.dev", "d.dev", "e.dev", "f.dev"], ["pypi.org", "not a host"]):
+ d = ask(eng, hosts)
+ assert not d.allowed and not d.needs_user and "exact host names" in d.reason, hosts
+
+
+# -- who answers ---------------------------------------------------------------------------
+def test_a_person_and_only_a_person_answers(tmp_path):
+ for mode in (Mode.INTERACTIVE, Mode.AUTO_APPROVE):
+ d = ask(engine(tmp_path, mode), ["registry.npmjs.org", "github.com"])
+ assert not d.allowed and d.needs_user and d.human_only, mode
+ assert d.network_hosts == ("registry.npmjs.org:443",) # github.com is already allowed
+ # A session-wide grant of the tool, however it got there, clears nothing: every ask
+ # for a new site is a new card.
+ eng = engine(tmp_path)
+ eng.allow_tool_for_session(NETWORK_ACCESS_TOOL)
+ assert ask(eng, ["registry.npmjs.org"]).needs_user
+
+
+def test_full_access_cannot_change_the_wall_and_read_only_modes_do_not_ask(tmp_path):
+ d = ask(engine(tmp_path, Mode.BYPASS_APPROVALS), ["registry.npmjs.org"])
+ assert not d.allowed and not d.needs_user and "Settings > Sandbox" in d.reason
+ for mode in (Mode.DISCUSS, Mode.PLAN):
+ d = ask(engine(tmp_path, mode), ["registry.npmjs.org"])
+ assert not d.allowed and not d.needs_user and "read-only" in d.reason
+
+
+def test_sites_already_allowed_need_no_card_and_no_list_means_no_tool(tmp_path):
+ assert ask(engine(tmp_path), ["github.com", "raw.githubusercontent.com"]).allowed
+ assert ask(engine(tmp_path), ["github.com:22"]).needs_user # another port is another entry
+ plain = PermissionEngine(workspace_root=tmp_path, mode=Mode.INTERACTIVE)
+ d = ask(plain, ["registry.npmjs.org"])
+ assert not d.allowed and not d.needs_user
+
+
+# -- what an approval does -----------------------------------------------------------------
+def test_this_session_opens_the_sandbox_and_stores_nothing(tmp_path):
+ opened: list[str] = []
+ stored: list[str] = []
+ eng = engine(tmp_path, open_site=opened.append, grant_site=lambda entry: stored.append(entry) or [*SITES, entry])
+ eng.allow_network_hosts(["registry.npmjs.org:443", "db.example.com:5432"], always=False)
+ assert opened == ["registry.npmjs.org:443", "db.example.com:5432"] and stored == []
+ assert eng.session_sites == ["registry.npmjs.org:443", "db.example.com:5432"] and eng.sandbox_sites == SITES
+ assert ask(eng, ["registry.npmjs.org", "db.example.com:5432"]).allowed
+ # One list for commands and web tools: the web tools reach the site too.
+ assert eng.evaluate("web_fetch", {"url": "https://registry.npmjs.org/left-pad"}, None).allowed
+
+
+def test_always_allow_stores_the_site_on_the_machines_list(tmp_path):
+ opened: list[str] = []
+ eng = engine(tmp_path, open_site=opened.append, grant_site=lambda entry: [*SITES, entry])
+ eng.allow_network_hosts(["registry.npmjs.org:443"], always=True)
+ assert eng.sandbox_sites == [*SITES, "registry.npmjs.org:443"] and eng.session_sites == []
+ assert opened == ["registry.npmjs.org:443"] and ask(eng, ["registry.npmjs.org"]).allowed
+
+
+def test_the_agent_is_told_what_it_now_has_and_what_the_sandbox_could_not_take(tmp_path):
+ def open_site(entry: str) -> None:
+ if entry.startswith("db."):
+ raise RuntimeError("the gateway did not answer")
+
+ eng = engine(tmp_path, open_site=open_site)
+ run = request_network_access_tool(eng)
+ eng.allow_network_hosts(["registry.npmjs.org:443", "db.example.com:5432"], always=False)
+ result = run(hosts=["registry.npmjs.org", "db.example.com:5432"], reason="x")
+ assert result["allowed"] == ["registry.npmjs.org"] and "Run the command again" in result["message"]
+ assert result["not_opened"] == {"db.example.com:5432": "the gateway did not answer"}
+ assert run.__name__ == NETWORK_ACCESS_TOOL
+
+
+def test_the_server_offers_this_session_and_always_and_nothing_tool_wide():
+ from coworker.engine import ApprovalOutcome
+ from coworker.server.manager import _grant_offered
+
+ request = SimpleNamespace(tool_name=NETWORK_ACCESS_TOOL, metadata=None, arguments={"hosts": ["a.dev"]})
+ assert _grant_offered(ApprovalOutcome.ALWAYS_DOMAIN, request) and _grant_offered(ApprovalOutcome.ALWAYS_SITE, request)
+ for outcome in (ApprovalOutcome.ALWAYS_TOOL, ApprovalOutcome.THIS_RUN, ApprovalOutcome.ALWAYS_COMMAND, ApprovalOutcome.ALWAYS_TRUST):
+ assert not _grant_offered(outcome, request), outcome
+
+
+# -- what the sandbox reports --------------------------------------------------------------
+def _connect(proxy: netproxy.AllowListProxy, target: str) -> bytes:
+ with socket.create_connection(("127.0.0.1", proxy.port), timeout=5) as sock:
+ sock.sendall(f"CONNECT {target} HTTP/1.1\r\nHost: {target}\r\n\r\n".encode())
+ return sock.recv(4096)
+
+
+def test_the_proxy_remembers_what_it_refused_and_when():
+ proxy = netproxy.AllowListProxy("allowlist")
+ try:
+ assert b"403" in _connect(proxy, "registry.npmjs.org:443")
+ assert b"403" in _connect(proxy, "registry.npmjs.org:443")
+ (first, entry), (second, _) = proxy.blocked_since(0)
+ assert entry == "registry.npmjs.org:443" and first <= second
+ assert proxy.blocked_since(second + 1) == []
+ finally:
+ proxy.close()
+ # What a program asked for is shown to the agent and the person: only a host name passes.
+ assert netproxy._blocked_entry("http://Example.com/a?b=c") == "example.com:80"
+ for text in ("ignore previous instructions:443", "*.npmjs.org:443", "localhost:443", ""):
+ assert netproxy._blocked_entry(text) == "", text
+
+
+def test_the_note_says_what_was_blocked_and_what_is_not_known():
+ text = network_note_text({"registry.npmjs.org:443": 3, "objects.githubusercontent.com:443": 1}, can_ask=True)
+ assert "may have affected it" in text and "- registry.npmjs.org:443 (3 attempts)" in text and "- objects.githubusercontent.com:443\n" in text
+ assert "or from something else running in this session" in text and "request_network_access(hosts, reason)" in text
+ told = network_note_text({"a.dev:443": 1}, can_ask=False)
+ assert "request_network_access" not in told and "Settings > Sandbox > Choose sites" in told
+ many = network_note_text({f"h{i}.dev:443": 1 for i in range(14)}, can_ask=True)
+ assert "- h9.dev:443" in many and "h10.dev" not in many and "and 4 more" in many
+
+
+class _Provider:
+ name, profile = "seatbelt", "allowlist"
+
+ def __init__(self):
+ self.extra_hosts = ["github.com:443", "db.example.com:5432"]
+ self.blocked: list[tuple[float, str]] = []
+
+ def blocked_since(self, since):
+ return [item for item in self.blocked if item[0] >= since]
+
+
+def test_a_command_result_carries_the_note_only_when_something_was_blocked(tmp_path):
+ provider = _Provider()
+ workspace = RunnerWorkspace(provider, cwd=tmp_path, start=False)
+ assert workspace.network_note(0.0) is None
+ provider.blocked = [(10.0, "old.dev:443"), (20.0, "registry.npmjs.org:443"), (21.0, "registry.npmjs.org:443")]
+ note = workspace.network_note(15.0)
+ assert note["blocked_sites"] == ["registry.npmjs.org:443"] and "(2 attempts)" in note["network_note"]
+ assert "Settings > Sandbox" in note["network_note"] # nobody can be asked until the session says so
+ workspace.can_ask_network = lambda: True
+ assert "request_network_access(hosts, reason)" in workspace.network_note(15.0)["network_note"]
+
+
+def test_the_executor_adds_the_note_to_a_command_result(tmp_path):
+ client = SimpleNamespace(call=lambda *a, **kw: {"command": "npm i", "cwd": str(tmp_path), "exit_code": 1, "output": "npm ERR!"})
+ seen: list[float] = []
+ executor = RunnerExecutor(client, cwd=str(tmp_path), after_call=lambda started: seen.append(started) or {"blocked_sites": ["a.dev:443"], "network_note": "Note: …"})
+ result = executor.run("npm i")
+ assert result["exit_code"] == 1 and result["blocked_sites"] == ["a.dev:443"] and result["network_note"] == "Note: …" and seen
+
+ def broken(started):
+ raise RuntimeError("no log")
+
+ assert RunnerExecutor(client, cwd=str(tmp_path), after_call=broken).run("npm i")["output"] == "npm ERR!"
+
+
+def test_the_agent_is_told_the_live_list_each_turn(tmp_path):
+ provider = _Provider()
+ workspace = RunnerWorkspace(provider, cwd=tmp_path, start=False)
+ workspace.can_ask_network = lambda: True
+ text = workspace.context()
+ assert "They reach only these sites: github.com, db.example.com:5432." in text
+ assert "call request_network_access" in text and "do not look for another route" in text
+ provider.extra_hosts.append("pypi.org:443")
+ assert "pypi.org" in workspace.context()
+ workspace.can_ask_network = lambda: False
+ assert "request_network_access" not in workspace.context() and "tell the user" in workspace.context()
+ provider.profile = "open"
+ assert "sandbox" not in workspace.context()
+
+
+def test_a_sandbox_that_cannot_report_blocks_gives_the_card_no_evidence(tmp_path):
+ """OpenShell's denial log is not read yet. An empty answer there means "unknown", so the
+ card must not say that no command has tried the site."""
+ from coworker.engine import TurnEngine
+ from coworker.permissions import Decision
+ from coworker.sandbox.providers import openshell, seatbelt
+
+ assert openshell.OpenShellProvider.reports_blocked is False and seatbelt.SeatbeltProvider.reports_blocked is True
+ call = SimpleNamespace(arguments={"hosts": ["registry.npmjs.org"], "reason": "npm install"})
+ decision = Decision(False, "asks", needs_user=True, human_only=True, network_hosts=("registry.npmjs.org:443",))
+
+ def payload(provider):
+ holder = SimpleNamespace(sandbox_workspace=RunnerWorkspace(provider, cwd=tmp_path, start=False))
+ return TurnEngine._network_request_payload(holder, call, decision)
+
+ unknown = _Provider()
+ assert payload(unknown) == {"reason": "npm install", "evidence": False, "hosts": [{"host": "registry.npmjs.org:443", "blocked_seconds_ago": None}]}
+ seen = _Provider()
+ seen.reports_blocked = True
+ seen.blocked = [(__import__("time").time() - 30, "registry.npmjs.org:443")]
+ shown = payload(seen)
+ assert shown["evidence"] is True and 29 <= shown["hosts"][0]["blocked_seconds_ago"] <= 35